sazr
sazr

Reputation: 25928

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?

Upvotes: 1

Views: 197

Answers (2)

Pieter
Pieter

Reputation: 1774

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);

Upvotes: 2

mdameer
mdameer

Reputation: 1540

You should declare another object of this to use it within callbacks:

var _this = this;

define this at first line of you widget class.

Upvotes: 0

Related Questions