gpt4 book ai didi

javascript - JQuery 等同于 MooTools bind(this)

转载 作者:可可西里 更新时间:2023-11-01 02:19:07 24 4
gpt4 key购买 nike

我正在尝试使用此 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com