Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
});
like image 637
Provster Avatar asked Aug 23 '13 16:08

Provster


1 Answers

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");
},
like image 61
Naftali Avatar answered Sep 18 '22 02:09

Naftali