javascriptjqueryjquery-eventsjquery-on

Attaching Events to an Empty Array with jQuery.on()


Another question where I get to murder barry.

Can you attach events to an empty array using jQuery's .on() ?

var barry = new Person();
var steve = new Person();
var paul = new Person();

var people = [];


function Person() {

}

Person.prototype.murder = function() {
    $(this).triggerHandler("murder");
}


/*
    If I apply .on to an empty array the event is never triggered why?
            $(people).on("murder", function(){
       console.log("call the police");
    })

 */

people.push(barry)
people.push(steve)
people.push(paul)

$(people).on("murder", function() {
    console.log("call the police");
})

barry.murder();​

Here's a fiddle suggesting you can't; but why not? I would of assumed that the array is the delegate object?


Solution

  • You're not binding events to an array. Calling the $ function on an array [a,b,c] is the same as $(a).add(b).add(c). And $([]) is the same as just $() (an empty jQuery object).