I can't read jQuery-UI widget factory options from a privat method

非 Y 不嫁゛ 提交于 2020-01-17 04:16:06

问题


I'm new with the jQueryUI widget factory, therefore it may be silliness what I'll ask. I'd like to create an ajax tooltip where I can set the url of the ajax call through an option but this option is not readable in the _mouseOver method which contains the ajax call.

    (function($) {
        $.widget("ui.tooltip", {
   options: {
        url: ''
    },
  _create: function() {
      alert(this.options.url); //it works
      this.element.bind({
        mouseenter: this._mouseOver
      });
    },
  _mouseOver: function() { 
      alert(this.options.url); //it dosen't works
    },
  ...

As I setup: $(".text").tooltip({url: "something" });

Can somebody help me, please.


回答1:


(function ($) {
    $.widget("ui.tooltip", {
        self: null,
        options: {
            url: ''
        },
        _create: function () {
            self = this;
            self.element.bind({
                mouseenter: self._mouseOver
            });
        },
        _mouseOver: function () {
            alert(self.options.url); // it should work
        }
    });
})(jQuery);

Using "this" inside _mouseOver refers to a current object inside the event function and not to the widget itself. You should create a variable and put the widget (this) on it, to be able to use it options in any event or method. You will find the same behavior when using a $.each() function in jQuery.




回答2:


In this case "this" context of _mouseOver function is element and not jquery widget. That's why you don't get options.url.

You can try using this code as a start:

_create: function() {
      alert(this.options.url); //it works
      this.element.tooltip = this;
      this.element.bind({
        mouseenter: this._mouseOver
      });
    },  
_mouseOver: function() { 
  alert(this.tooltip.options.url); //it dosen't works
},

It's not tested.



来源:https://stackoverflow.com/questions/11498367/i-cant-read-jquery-ui-widget-factory-options-from-a-privat-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!