Using jquery to resolve events on regular JS objects

I have several javaScript classes (ctor + prototype methods) that I want their instances to generate evnets.

so that code using this class can look something like this:

var instance=new SomeObject(); instance.on('customEventName',function(event){do_stuff()} 

I work in a jQuery environment and for the user interface elements that I use .trigger and .on, which works fine for me, I wandered what would be the best way to implement the same thing with respect to regular objects.

I am thinking of setting up a map of $ .Callbacks () objects based on the name of the custom event and adding .on and .trigger to the prototype object. Or maybe I can just save the eventPoint instance variable initialized to empty $ () and hook the .on and .trigger methods from the prototype to this eventPoint object.

Any other / best ideas?

+7
source share
2 answers

jQuery actually allows you to do this very simply, as with the DOM element:

 var instance = new SomeObject(); $(instance).on("customEventName", function () { do_stuff(); }) // Later... $(instance).trigger("customEventName"); 

All event handlers are stored in the jQuery internal data store, and jQuery adds a property to your object that contains the data index in that store.

+6
source

I would suggest using the trunk, as it handles events well and can also meet your requirements.

http://backbonejs.org/#Events

0
source

All Articles