相当于MooTools的JQuery bind(this)

| 我正在尝试使用此类插件在JQuery中重写Mootools工具提示类。实例化我的课程后,我会将事件侦听器附加到目标链接,该链接将淡化工具提示。 在事件回调中,JQuery将关键字\“ this \”分配给事件的目标,因此要保留对类的属性的引用,请使用apply()将\“ this \”设置为表示类实例。这显然是Mootools方便的bind()函数的JQuery中的对应项。 不幸的是,当我使用apply()时,我丢失了回调的event参数。例如,在此行中,第二行出现错误“ e is undefined \”。
this.target.bind(\'click\', function(e){
    e.preventDefault();
    var tip = this.opts.tip;
    tip.fadeOut(500, function(){
        tip.bind(\'click\', function(){
            showing = false;
        })
    });
}.apply(this))
我在这里错过了把戏吗?有人知道解决此问题的方法吗? 谢谢 弗雷德     
已邀请:
        TBH,即您所说的
mootools
.bind
在ES5中仅为
Function.bind
-在支持js 1.8.5 +规范的浏览器中本机可用。 MooTools只是增强了尚不具备的浏览器,但允许本机实现保留在原型中(如果可用)。 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind 您可以轻松地将其实现为
Function.prototype.bind
装饰器(如果本机不可用),并将其用作上面的示例所示:
// Function.prototype.bind polyfill
if ( !Function.prototype.bind ) {

  Function.prototype.bind = function( obj ) {
    if(typeof this !== \'function\') // closest thing possible to the ECMAScript 5 internal IsCallable function
      throw new TypeError(\'Function.prototype.bind - what is trying to be bound is not callable\');

    var slice = [].slice,
        args = slice.call(arguments, 1), 
        self = this, 
        nop = function () {}, 
        bound = function () {
          return self.apply( this instanceof nop ? this : ( obj || {} ), 
                              args.concat( slice.call(arguments) ) );    
        };

    bound.prototype = this.prototype;

    return bound;
  };
}
如您所见,它比简单的
.apply
/
.call
涉及的更多 要考虑的一件事是,如果您需要使用bind还是可以保存引用。 例如。
var self = this;
this.target.bind(\"click\", function(e) {
    var tip = self.opts.tip;
});
它的占用空间比函数绑定要小。它还为您提供了将ѭ9用作触发元素(
event.target === this
)的正确参考。在mootools-core中,您会发现这种模式比绑定模式更常见-尽管当您想将事件分配给类方法时通常需要绑定,例如:
this.element.addEvents({
    click: this.showTip.bind(this),
    mouseleave: this.hideTip.bind(this)
});
在这种情况下,尽管您可以将参考重写为
var self = this;
this.element.addEvents({
    click: function(e) {
        self.showTip(e);
    }
});
jQuery的特定实现为ѭ13-http://api.jquery.com/jquery.proxy/     
        在某个元素上发生的所有事件(例如\'click \'是其中之一)应具有指向该元素的target属性
var $this = $(e.target); // $this will be the clicked element
JSFiddle     

要回复问题请先登录注册