And*_*lly 11 javascript jquery mootools javascript-events
我正在尝试使用此类插件在JQuery中重写Mootools工具提示类.当我的类被实例化时,我将一个事件监听器附加到目标链接,这将淡出工具提示.
在事件回调中,JQuery将关键字"this"分配给事件的目标,因此要保持对我正在使用的类的属性的引用apply()将"this"设置为表示类实例.这显然是Mootools的方便bind()函数的JQuery中的对应物.
不幸的是,当我使用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))
Run Code Online (Sandbox Code Playgroud)
我在这里错过了一招吗?有没有人知道解决这个问题的方法?
谢谢Fred
Dim*_*off 19
TBH,mootools .bind正如你所说的那样只是Function.bind在ES5中 - 并且可以在支持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;
};
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,它比一个简单的.apply/ 更多涉及.call
需要考虑的一件事是,如果您需要使用bind或者您可以保存引用.
例如.
var self = this;
this.target.bind("click", function(e) {
var tip = self.opts.tip;
});
Run Code Online (Sandbox Code Playgroud)
无论如何,这比功能绑定的占地面积更小.它还为您提供了this作为触发元素(event.target === this)的正确引用.你会发现这种模式在mootools-core中比绑定更常见 - 虽然当你想要将事件分配给类方法时经常需要绑定,例如:
this.element.addEvents({
click: this.showTip.bind(this),
mouseleave: this.hideTip.bind(this)
});
Run Code Online (Sandbox Code Playgroud)
在这种情况下,虽然您可以将其重写为,但保存引用将不起作用
var self = this;
this.element.addEvents({
click: function(e) {
self.showTip(e);
}
});
Run Code Online (Sandbox Code Playgroud)
jQuery特定的实现是proxy- http://api.jquery.com/jquery.proxy/
| 归档时间: |
|
| 查看次数: |
4185 次 |
| 最近记录: |