Search code examples
javascriptjqueryjquery-uijquery-pluginsjquery-widgets

Trouble with Jquery widget


I have a widget like this

$.widget("ui.myWidget", {
    //default options
    options: {
        myOptions: "test"
    },
    _create: function () {
        this.self = $(this.element[0]);
        this.self.find("thead th").click(function () {
            this.self._headerClick(); //how do I do this!!!
        });
        this.self._somethingElse();
    },
    _headerClick: function (){
    },
    _somethingElse: function (){
    },
.
.
.

The line this.self._headerClick(); throws an error. This is because in that context this is the th element that was clicked. How do I get a reference to the _headerClick function?


Solution

  • Store the scope of desired this within a variable.

    $.widget("ui.myWidget", {
        //default options
        options: {
            myOptions: "test"
        },
        _create: function () {
            var that = this; // that will be accessible to .click(...
            this.self = $(this.element[0]);
            this.self.find("thead th").click(function () {
                that._headerClick(); //how do I do this!!!
            });
            this.self._somethingElse();
        },
        _headerClick: function (){
        },
        _somethingElse: function (){
        },