rniemeyer / knockout-postbox

A small library that uses Knockout's native pub/sub capabilities to facilitate decoupled communication between separate view models or components.
MIT License
348 stars 55 forks source link

Subscribing / Unsubscribing using ko.postbox #36

Closed sbrassard closed 9 years ago

sbrassard commented 9 years ago

rniemeyer,

I am currently using postbox to subscribe to events like this for specific reasons: ko.postbox.subscribe("SomeTopic", function() { foo() }, {});

What I would like to know is, can a subscribed topic be unsubscribed? I dont want to call ko.postbox.reset() and lose all of my subscriptions, I just want to unsubscribe one specific topic, something like:

ko.postbox.unsubscribe("SomeTopic");

I didnt see anything in the documentation regarding anything closely similar, but that would be great if that could be added in. Unless, there is a better way to unsubscribe a specific topic?

Thanks, Steve

rniemeyer commented 9 years ago

Hi Steve- The ko.postbox.subscribe API returns a subscription object that has a dispose method. This allows you to subscribe to the same topic multiple times (with different handlers) and unsubscribe specific handlers. So, it would look like:

var sub = ko.postbox.subscribe("myTopic", myHandler);

// sometime later
sub.dispose();

Hope that helps!

sbrassard commented 9 years ago

Ahh...thanks! I appreciate the quick response!