Provster
Provster

Reputation: 125

Event handlers inside javascript object literal

I'm trying to create an object and assign click handlers from within it. I have realised I can't do it how I want due to "this" becoming associated with the button, instead of the object literal, breaking access to the functions.

"Uncaught TypeError: Object # has no method 'clearSelection'"

Please see the below fiddle.

http://jsfiddle.net/ebKk8/

And here is the code for reference. It's not supposed to do anything useful at this stage, except illustrate the problem :)

function ThingConstructor(someData) {
    var button = $("#someButton");
    return {

        initialise: function () {
            button.click(function () {
                // I want "this.clearSelection();" to target the 
                // "clearSelection" function below.
                // Instead, it targets the button itself.
                // How can i refer to it?
                this.clearSelection();
            });
        },

        clearSelection: function () {
            this.populateList($("#stuff"), someData);
            $("#adiv").empty();
            console.log("clearSelection");
        },

        populateList: function (var1, var2) {
            //do something to a list
        }
    }
}

$(function () {
    var test = ThingConstructor("someData");
    test.initialise();
});

Upvotes: 6

Views: 2117

Answers (1)

Naftali
Naftali

Reputation: 146350

The this in your click handler is the DOMElement and not your object.

Try this:

initialise: function() {
    var _this = this; //reference to this object
    button.on('click', function () {
        _this.clearSelection();  // use _this
    }).appendTo("body");
},

Upvotes: 11

Related Questions