JavaScript Framework to just listen/subscribe & trigger/fire custom events similar to Backbone.Events?
Just curious if there was any JS mini/micro framework/lib that I am missing...
Backbone.Events does this, but any small framework/lib that just does this, or does it simpler/better?
Thanks.
JavaScript Framework to just listen/subscribe & trigger/fire custom events similar to Backbone.Events?
Just curious if there was any JS mini/micro framework/lib that I am missing...
Backbone.Events does this, but any small framework/lib that just does this, or does it simpler/better?
Thanks.
Share Improve this question asked Oct 15, 2012 at 19:18 Quang VanQuang Van 12.1k12 gold badges62 silver badges61 bronze badges 5- Interpretation: what does the author mean? – yodog Commented Oct 15, 2012 at 19:21
- 1 Backbone.Events is pretty simple, you could extract it in a few minutes or duplicate it in a couple hours. – mu is too short Commented Oct 15, 2012 at 19:30
-
1
you could write your own very easily by just keeping an internal object of
(eventName, callback)
pairs and exposingpublish
andsubscribe
functions. – jbabey Commented Oct 15, 2012 at 19:48 - making your own would be an awesome learning experience as well. it's surprisingly easy to implement. just as mu is too short said, you can just pull Backbone.Events out of the library. It's 80 lines of code and 32 lines of ments. – Cory Danielson Commented Oct 16, 2012 at 11:50
- amplifyjs./api/pubsub – Cory Danielson Commented Oct 16, 2012 at 11:52
2 Answers
Reset to default 6Simplest way - provided you're usign jQuery - is to use jQuery.trigger (equivalent to publish) and jQuery.bind (equivalent to subscribe). Also jQuery.unbind (to unsubscribe).
You can use them with DOM events as well as custom events.
//Subsribe to my custom Event
$(document).bind('MyCustomEvent', function() {
alert('Reacting to my custom event ..');
});
// .... somewhere else in the code, publish the event
jQuery.event.trigger('MyCustomEvent');
//or $(document).trigger('MyCustomEvent');
[Update from jquery documentation]
(As of jQuery 1.7, the .on() and .off() methods are preferred to attach and remove event handlers on elements.)
I worked with Chaplin which uses the publish/subscribe pattern.
You can look for some "mediators" like Core.js, PubSub or Signal-js.
Referencing and user feedbacks in this post.