微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – JQuery相当于MooTools绑定(this)

我试图使用这个 class plugin在JQuery中重写一个Mootools工具提示类.当我的类被实例化时,我将事件监听器附加到目标链接,这将淡出工具提示.

在事件回调中,JQuery将关键字“this”分配给事件的目标,所以为了保持对类的属性的引用,我使用apply()来设置“this”来表示类实例.这显然是Mootools的handy bind()函数的JQuery中的对应项.

不幸的是当我使用apply()我失去了回调的事件参数.例如,在这一点我得到一个“e是未定义”的错误在第二行.

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有一点更多的参与

需要考虑的一件事是,如果您需要使用绑定,或者您可以保存参考.

例如.

var self = this;
this.target.bind("click",function(e) {
    var tip = self.opts.tip;
});

这样做比功能绑定还要小.它也为您提供了一个正确的引用,作为触发元素(event.target === this).你会发现这个模式在mootools-core中比bind一般 – 尽管如果要将事件分配给类方法,通常需要绑定,例如:

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特定的实现是代理 – http://api.jquery.com/jquery.proxy/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐