javascript - JQuery 等同于 MooTools bind(this)

标签 javascript jquery mootools mootools-events

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

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

不幸的是,当我使用 apply() 时,我丢失了回调的事件参数。例如,在这一点中,我在第二行收到“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 只是增强了还没有它的浏览器,但让 native 实现保留在原型(prototype)上——如果可用的话。

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind

如果 native 不可用,您可以轻松地将其实现为 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;
});

无论如何,这比函数绑定(bind)占用空间更小。它还为您提供了对 this 作为触发元素的正确引用 (event.target === this)。你会发现这种模式在 mootools-core 中比 bind 模式更常见 - 尽管当你想将事件分配给类方法时通常需要 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 特定实现是 proxy - http://api.jquery.com/jquery.proxy/

关于javascript - JQuery 等同于 MooTools bind(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6321152/

相关文章:

javascript - 为什么我会在一个事件上多次执行?

jquery - Javascript 框架在 Firefox Ubuntu 8.04 中卡住,不知道是什么原因

javascript - Mootools 脚本不兼容

javascript - 如何在QUnit中加载不同的html文件?

javascript - 背景图片滑动效果

javascript - 简单的 JavaScript 事件 : alert using inline and traditional methods

javascript - 如何加载使用 ajax 编写的处理脚本?

jquery - 使用 jQuery 设置输入的实际值属性

javascript - Ext.dom 未定义 Sencha Touch

javascript - JQuery、函数编排