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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With