jQuery .click event binding to multiple dynamic elements
Within my code I am trying to bind a click event to a dynamically created <a> element. Each element's click event has specific metadata used within the handler. Rather than appending dynamic attributes in HTML (there's a lot of them), I have an array of objects. This is also why I've not used a global event handler.

The code example may explain that better!

The problem I am having, is the click event is only called for the last created element. Here's some code:


    var MyObject = {
        additionalAttributes: { ... }

        getNode: function() {
            if (this.node) return this.node;
            var a = this.node = $(document.createElement("a"));

            // ... building the 'a' here.

            a.click(function(e) {
               e.preventDefault();
               alert(this.additionalAttributes.something);
            });
        }
    }

Get Node is called like so:

    var x = new MyObject( ... );
    $('#someDivElement').append(x.getNode());


This works nicely, but if I call the .append() with multiple instances of 'x', the click event is only fired for the last element added to the container.

Can anyone explain what I'm doing wrong here, or perhaps suggest a better approach to the overal problem?
jQuery .click event binding to multiple dynamic elements
===

Within my code I am trying to bind a click event to a dynamically created <a> element. Each element's click event has specific metadata used within the handler. Rather than appending dynamic attributes in HTML (there's a lot of them), I have an array of objects. This is also why I've not used a global event handler.

The code example may explain that better!

The problem I am having, is the click event is only called for the last created element. Here's some code:


    var MyObject = {
        additionalAttributes: { ... }

        getNode: function() {
            if (this.node) return this.node;
            var a = this.node = $(document.createElement("a"));

            // ... building the 'a' here.

            a.click(function(e) {
               e.preventDefault();
               alert(this.additionalAttributes.something);
            });
        }
    }

Get Node is called like so:

    var x = new MyObject( ... );
    $('#someDivElement').append(x.getNode());


This works nicely, but if I call the .append() with multiple instances of 'x', the click event is only fired for the last element added to the container.

Can anyone explain what I'm doing wrong here, or perhaps suggest a better approach to the overal problem?