繁体   English   中英

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

[英]jQuery-ui widget factory, event handlers and that

我最近一直在开发一些jQuery小部件,但有2件事困扰着我,因此我来告诉您,希望您有一种更好的方法。

1)我非常喜欢使用“ that”代替它的事实。 使代码更加清晰,并避免了很多错误。 为简单起见,我始终将“ that”用作窗口小部件。 但是我不知道如何使我的“那个”全局,所以我要做的是:

$.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)这实际上与我的第一个问题相关联,并且对它的回答应该足够了:对于我的事件处理程序,我经常需要使用“ that”来调用例如的方法。 所以我现在要做的是

 $.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的整个初始化移出该对象。

这些是很开放的问题。 我真的在试图找到一种方法来使我的jquery小部件真正清晰和可维护,并且我很好奇知道人们的行为。

非常感谢您对此的意见。

为了扩展我的评论,以下是您可以绑定处理程序以保留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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM