7

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 ?

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

many thanks this does all I need. I would have never try this after reading here: api.jquery.com/Types/#jQuery that "A jQuery object contains a collection of Document Object Model (DOM) elements that have been created from an HTML string or selected from a document".
any chances, you know how now list all events bound to some object?
0

I would suggest using backbone as it handles the events pretty well and might also fit in your requirement.

http://backbonejs.org/#Events

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.