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

时间:2012-10-05 19:23:31

标签: javascript jquery jquery-ui jquery-ui-widget-factory

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

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

$.widget("widgetName", {
    method1: function() {
        var that = this;
    },
    method2: function() {
        var that = this;
    }
});

正如你所看到的那样,代码很重而且不是更好。我想知道我是否有效:

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

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

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

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

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

非常感谢您对此的看法。

1 个答案:

答案 0 :(得分: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() {}
 });

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

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

编辑:如果你真的想要一个全局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);
相关问题