How to get widget instance inside jQuery widget?

I am working on keyboard widgets for a project, I am expanding $.ui.mouse. I need click behavior (not called _mouseCapture). I'm having difficulty returning this.optionsinside of it. See the following code blocks:

$.widget("ui.keyboard", $.ui.mouse, {
    widgetEventPrefix: "keyboard",
    options: {
        [...]
    },
    [...],
    _create : function() {
        this.element.bind('click.'+this.widgetName, this._mouseClick);
    },
    _mouseClick: function(e) {
        // how do i get this.options here
    }
});

This is best done:

$.widget("ui.keyboard", $.ui.mouse, {
    widgetEventPrefix: "keyboard",
    options: {
        [...]
    },
    [...],
    _create : function() {
        var self = this;
        this.element.bind('click.'+this.widgetName, function(e) { self._mouseClick(e, self); });
    },
    _mouseClick: function(e, self) {
        // how do i get this.options here -> self.options
    }
});

Or that:

$.widget("ui.keyboard", $.ui.mouse, {
    widgetEventPrefix: "keyboard",
    options: {
        [...]
    },
    [...],
    _create : function() {
        this.element.bind('click.'+this.widgetName, this._mouseClick);
    },
    _mouseClick: function(e) {
        var self = $.data(this, "keyboard");
        // how do i get this.options here -> self.options
    }
});

I had problems with the latter when I try to start it manually. $ .data does not work unless I start clicking on this.element(which is pretty logical).

Are there any other ways? Which one is best to choose?

Thank,

+3
source share
1 answer

You can call an anonymous function that returns an object, for example:

$.widget("ui.keyboard", $.ui.mouse, function(){
  var self;

  return {
    widgetEventPrefix: "keyboard",
    options: {
      [...]
    },
    _create : function() {
      self = this;
      this.element.bind('click.'+this.widgetName, function(e) { self._mouseClick(e, self); });
    },
    _mouseClick: function(e, self) {
      // do something with self.options
    }
  }
}());

This way you have access to yourself from _mouseClick -

+1
source

Source: https://habr.com/ru/post/1791868/


All Articles