Question

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?

Was it helpful?

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 (){
    },

OTHER TIPS

Untested, but maybe something like this:

_create: function () {
    var self = this,
        $elem = $(self.element[0]);

    $elem.find("thead th").click(function() {
        self._headerClick();
    });

    self._somethingElse();
},
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top