Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Framework to just subscribe & fire custom events?

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.

like image 942
Quang Van Avatar asked Jan 15 '23 07:01

Quang Van


1 Answers

Simplest 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.)

like image 90
kabaros Avatar answered Jan 19 '23 00:01

kabaros