Search code examples
backbone.js

How to check whether that object has an event?


My example :

var object = {
    msg: 'context obj'
};
var object2 = {
    msg: 'other context obj2'
};
_.extend(Object.prototype, Backbone.Events);
object.on("alert:boom", function() {
    console.log("run " + this.msg);
}, object2);
object.on("all", function(eventName) {
    console.log('all');
});
object.trigger("alert:boom");
object.trigger("alert:riri"); //Why  called ALL ????

How to check whether that object has an event ?
I hope for your help.


Solution

  • It's unclear if your question is "How to check whether that object has an event ?" or "//Why called ALL ????" -- @AlexacderImra has answered the last one.

    It is not recommended you check internal variables but it is very unlikely this will chage - the event array is _events so you can do:

    if (myObject._events['myeventname'])
    

    To check for a particular event, or:

    if (myObject._events.length)
    

    To check if there are any events.

    It would be best to wrap that functionality in a function so that in the event it changes in future versions of Backbone you only have to update the logic in one place.