Search code examples
javascriptjqueryfunctionobjectexecute

jQuery object-oriented created dom element and add event listener


I have a little problem. I've created some element in an object and that works fine. But now I want to add some EventListeners to execute a function inner my object, the problem is that I cannot execute the function "setSelection". ("this" is not the "this" of the object, but the "this" of the event inner the click-function).

function Object() {
    this.init = function () {
        // delete table
        // ...
        // set table
        $('tr').append('<td id="1">test</td>');

        $('td').click(function() {
            // execute setSelection
        });
    }

    this.setSelection = function(x) {
        alert('You clicked id ' + x);
    }
}

$(document).ready(function() {
    x = new Object();
    x.init();
});

Solution

  • You can fix this by storing the reference of this in the outer scope to a variable that you can use in the click event handler:

    function Object() {
        var _this = this;
    
        this.init = function () {
            // delete table
            // ...
            // set table
            $('tr').append('<td id="1">test</td>');
    
            $('td').click(function() {
                _this.doSomething();
            });
        }
    
        this.setSelection = function(x) {
            alert('You clicked id ' + x);
        }
    }