Tot*_*ile 6 jquery plugins this
我想创建一个全景滑块作为jQuery插件,我有以下代码:
$.fn.panorama = function(settings) {
var myPanorama = this;
..
this.mousedown(function(e){
//do stuff
$(this).css... //this all work
}
//Call mouseup on document in case user lets go of mouse outside draggable object
$(document).mouseup(function(){
$(myPanorama).easeDragging(); //works but probably not the way to do it
this.easeDragging(); //ideal but refers to wrong object
});
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我如何引用通话中的this
对象$(document).mouseup
?
因为它认为this
是文档本身而不是附加到插件的对象.
现在我只是制作一个变量而且它有效,但必须有更好的方法!
谢谢!
实际上,你实现它的方式是最简单的方法 - 存储对此的引用:
var myPanorama = this;
// ...
myPanorama.easeDragging();
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用jQuery.proxy()来设置函数的上下文(感谢@Nick):
$(document).mouseup($.proxy(function(){
this.easeDragging();
}, this));
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用ECMAScript第5版.bind()方法,虽然你需要将它添加到Function原型中,以便在不支持的浏览器中工作:
// From Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
Function.prototype.bind = function(){
var fn = this, args = Array.prototype.slice.call(arguments),
object = args.shift();
return function(){
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
}
Run Code Online (Sandbox Code Playgroud)
然后您可以在代码中使用它,如下所示:
$(document).mouseup((function(){
this.easeDragging();
}).bind(this));
Run Code Online (Sandbox Code Playgroud)