简体   繁体   中英

jQuery: How to attach an event to newly created element inside class

I'm trying to create a Object class that will take data and create a list of elements. I also want to attach a click event on the new LI's that fires a method of the class. However, when using the

el.click(function() {
    this.method();
});

this no-longer references the Class, so clicking on the li gives you an undefined method error. Suggestions on how to attach the class method to the newly create elements?

JS Code:

if (typeof Object.create !== 'function') {
    Object.create = function(o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

var base = {
    init: function(data) {
        this.data = data;
        this.show_data();
    },


    show_data: function() {

        for (i = 0; i < this.data.bindings.length; i++) {

            var $item = $('<li>' + this.data.bindings[i].ircEvent + '</li>');
            $item.click(function() {
                this.show_clicked(i);
            });
            $('#it').append($item);
        }
    },

    show_clicked: function(index) {
        console.log('clicked in method');
    }
};

var extended = {

    show_alert: function() {
        alert('second class');
    }
};


var myObj = {
    "bindings": [
        {
        "ircEvent": "PRIVMSG",
        "method": "newURI",
        "regex": "^http://.*"},
    {
        "ircEvent": "PRIVMSG",
        "method": "deleteURI",
        "regex": "^delete.*"},
    {
        "ircEvent": "PRIVMSG",
        "method": "randomURI",
        "regex": "^random.*"}
    ]
};

$(document).ready(function() {

    var baseObj = Object.create(base);
    baseObj.init(myObj);

});

Fiddle: http://jsfiddle.net/kmfstudios/EwC3r/5/

In order to make your method work in the click function, just reference your global variable that contains the object.

The line:

    this.show_clicked(i);

should be changed to:

   base.show_clicked(i);

If you want your index value to be displayed in the final result, you'll have to either pass that as data, or use jquery to determine which index was clicked.

Here is an updated fiddle that works - http://jsfiddle.net/EwC3r/4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM