jQuery-ui小部件工厂,事件处理程序和那

cha*_*rly 2 javascript jquery jquery-ui jquery-ui-widget-factory

我最近一直在开发一些jQuery小部件,但有两件事困扰着我,所以我来找你,希望你能有更好的方法去做.

1)我非常喜欢使用"那个"而不是这个.使代码更清晰,避免相当多的错误.为了简化我总是使用"那个"作为小部件.但是我不知道如何让我的"那个"全球化,所以我所做的是:

$.widget("widgetName", {
    method1: function() {
        var that = this;
    },
    method2: function() {
        var that = this;
    }
});
Run Code Online (Sandbox Code Playgroud)

正如你所看到的那样,代码很重,并没有那么好.我想知道我是否有效:

 var that = $.widget("widgetName", {
     method1: function() {
         //do something
     },
     method2: function() {
         //do something
         that.method1();
     }
  });
Run Code Online (Sandbox Code Playgroud)

或者这会造成任何问题吗?如果这是不可能的,您认为最好的方法是什么?

2)这真的与我的第一个问题有关,它的答案应该足够了:对于我的事件处理程序,我经常需要使用我的"那个"来调用方法,例如.所以我现在做的是

 $.widget("widgetName", {
     _handlers: {},
     _create: function() {
         var that = this;
         that._handlers: {
             handler1: function(e) { 
                 //do something
                 that.method();
             } //...
         };
         that.on("event", that._handlers.handler1);
     },
     method: function() {}
 });
Run Code Online (Sandbox Code Playgroud)

你看到我能做到这一点的更好方法吗?我最大的需求是能够将that._handlers的整个初始化移出that._create

这些是非常开放的问题.我真的想找到一种方法让我的jquery小部件非常清晰和可维护,我很想知道人们如何做.

非常感谢您对此的看法.

use*_*654 7

为了扩展我的评论,这里是你如何绑定你的处理程序来保存 this

 $.widget("widgetName", {
     _handlers: {},
     _create: function() {
         this._handlers.handler1 = $.proxy(function(e) { 
                 //do something
                 this.method();
         }, this);
         this.element.on("event", this._handlers.handler1);
     },
     method: function() {}
 });
Run Code Online (Sandbox Code Playgroud)

或者您可以交换它,允许轻松覆盖第三方开发人员的处理程序:

 $.widget("widgetName", {
     _handlers: {
         handler1: function(e) { 
             //do something
             this.method();
         }
     },
     _create: function() {
         this.element.on("event", $.proxy(this._handlers.handler1,this));
     },
     method: function() {}
 });
Run Code Online (Sandbox Code Playgroud)

编辑:如果你真的想要一个全局that变量,这里有一种方法可以做到这一点而不会污染全局范围:

(function($){
     var that;
     $.widget("widgetName", {
         _handlers: {
             handler1: function(e) { 
                 //do something
                 that.method();
             }
         },
         _create: function() {
             that = this;
             this.element.on("event", this._handlers.handler1);
         },
         method: function() {}
     });
})(jQuery);
Run Code Online (Sandbox Code Playgroud)