Subtopic provides topic-based PubSub for javascript. Originally based on Peter Higgins' port from Dojo to JQuery and updated with support for message chaining inspired by Morgan Roderik's PubSubJS.
Vanilla javascrip:
NuGet here: http://nuget.org/packages/Subtopic.js
subtopic.subscribe(topic, callback)
subtopic.unsubscribe(topic)
subtopic.publish(topic, [payload])
Underscore:
NuGet here: http://nuget.org/packages/Underscore-Subtopic.js
_.subscribe(topic, callback)
_.unsubscribe(topic)
_.publish(topic, [payload])
jQuery:
NuGet: http://nuget.org/packages/JQuery-Subtopic.js
$.subscribe(topic, callback)
$.unsubscribe(topic)
$.publish(topic, [payload])
Performance
Check out the official performance comparison here:
http://jsperf.com/pubsubjs-vs-jquery-custom-events/51
Topic chaining
To use topic chaining divide your topics using forward slashes e.g. app/region/module/event. A subscriber will execute the callback function for the subscribed topic and any sub-topics.
The following publications will each invoke the callback for a subscription to app/region:
$.publish("app/region", [])
$.publish("app/region/module", [])
$.publish("app/region/module/event", [])
If you do NOT require topic chaining I would recommend using Peter Higgins´ port from Dojo here: https://github.com/phiggins42/bloody-jquery-plugins
Examples
$(function() {
$.subscribe("app/region", function() {
alert("Sub to app/region: " + arguments[0]);
});
$.subscribe("app", function() {
alert("Sub to app: " + arguments[0]);
});
$.publish("app/region/module", ["Pub in module", "arg2"]);
$.publish("app/region", ["Pub in region", "arg2"]);
$.publish("app", ["Pub in app", "arg2"]);
});​
JsFiddle here: http://jsfiddle.net/P8dQs/3/