Jon Wells
Jon Wells

Reputation: 4259

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?

Upvotes: 1

Views: 762

Answers (2)

Pointy
Pointy

Reputation: 413866

You can, but jQuery doesn't magically synthesize triggering methods for you.

people.trigger("murder");

It's also not going to work to trigger events on values that happen to be in the array; there's no event bubbling from array element to the containing array. Event bubbling works in the DOM, not on JavaScript data structures.

edit — oh sorry I see now that you've created your own .murder() API. Fine then, but you've still got the issue with event bubbling.

There's no firm relationship between an object and any array that happens to contain a reference to it. You could extend your API so that your "Person" objects could know where to send the events.

edit again — oh well I feel dumb now - this really doesn't have anything to do with an array as an object. When you wrap a jQuery object around an array instance, that's interpreted by the library as a request to treat the elements of the array as the members of the jQuery object. Thus, when you add the event handler, the array doesn't really have anything to do with it: you're adding the handler to the individual elements.

Upvotes: 2

thorn0
thorn0

Reputation: 10427

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).

Upvotes: 3

Related Questions