1

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?

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

var _this = this;

define this at first line of you widget class.

1 Comment

can you elaborate where exactly? Should it be above _create: ... because that gives a compiler error (because its in a map/object). Where exactly?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.