Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jquery to allow events on regular JS Objects

I have some javaScript Classes ( ctor+prototype methods) that I want their instances to be able to emit evnets.

so that the code using this class could so something like:

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

I am working in a JQUery environment and for UI elements I am using .trigger and .on which works great for me, I was wandering what would be the best way to implement the same feel with respect to regular objects.

I am thinking of either setting a map of $.Callbacks() objects based on the custom event name, and adding .on and .trigger to by object's prototype Or maybe I can just hold an eventsPoint instance variable initialized to an empty $() and wire up the .on and .trigger methods from the prototype to this eventsPoint object.

Any other / better ideas ?

like image 622
epeleg Avatar asked Feb 02 '12 09:02

epeleg


1 Answers

jQuery actually allows you to do this very simply, just like you would for a DOM element:

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

// Later...
$(instance).trigger("customEventName");

All event handlers are stored in jQuery's internal data store, and jQuery adds a property to your object that holds the index of the data within that store.

like image 133
Andy E Avatar answered Oct 16 '22 04:10

Andy E