Problem with jQuery widget

I have such widgets

$.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 string this.self._headerClick();throws an error. This is because, in this context this, the element ththat was clicked. How to get a link to the _headerClick function?

+3
source share
2 answers

Save the area of ​​the required thisinside the 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 (){
    },
+6
source

Unconfirmed, but there might be something like this:

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

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

    self._somethingElse();
},
+2
source

All Articles