Jake M Jake M - 3 months ago 14
Javascript Question

Access JQuery UI Widget from within Click callback function

My JQuery-UI widget should append a div to itself when clicked. But my button callback doesn't have access to

this.element
- it's undefined because I assume
this
refers to the button and not my widget. Please see the simple code below for a better description:

(function ($) {

$.widget( "my.myWidget", {

_create: function () {

this.element.click(this.addRow);
},

addRow: function(evt) {

// this.element is undefined?
console.log("Is this.element defined: " + this.element != undefined);

// cant append to this.element
$('<div></div>')
.appendTo(this.element);
}
});
})(jQuery);


How can I access the widget (
this.element
) inside my click callback function?

Answer

The reason it does not work is because the this.element.click listener callback is called from within a different scope. Therefore the scope from within the addRow is not the widget.

There are two ways of solving this problem.

Option 1: By storing this in a variable, so you can access it from within another scope. For example:

(function ($) {
    $.widget( "my.myWidget", {

        _create: function () {
            var self = this;
            this.element.click(function() {
                self.addRow();
            });
        },

        addRow: function(evt) {

            // this.element is undefined?
            console.log("Is this.element defined: " + this.element != undefined);

            // cant append to this.element
            $('<div></div>')
                    .appendTo(this.element);
        }
    });
})(jQuery);

Option 2: By binding the this scope to the this.addRow function object:

(function ($) {

    $.widget( "my.myWidget", {

        _create: function () {
            this.element.click(this.addRow.bind(this));
        },

        addRow: function(evt) {

            // this.element is undefined?
            console.log("Is this.element defined: " + this.element != undefined);

            // cant append to this.element
            $('<div></div>')
                    .appendTo(this.element);
        }
    });
})(jQuery);
Comments