2010-08-19 63 views
5

我想箱子全景滑块作为一个jQuery插件,我有以下代码..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 
}); 

    } 

我的问题是我如何参考到$(document).mouseup调用中的“this”对象?

因为它认为“this”是文档本身,而不是附加到插件的对象。

现在我只是做一个变量,它的工作原理,但必须有更好的方法!

谢谢!

回答

7

其实,你所取得的方式,做到这一点最简单的方式 - 存储参考这个

var myPanorama = this; 

// ... 

    myPanorama.easeDragging(); 

或者,您可以使用jQuery.proxy()设定的功能的情况下(感谢@Nick):

$(document).mouseup($.proxy(function(){ 
    this.easeDragging(); 
}, this)); 

的另一种方式做到这一点是使用ECMAScript的第5版.bind()实现方法具d,但你需要它添加到函数原型为它在不受支持的浏览器:

// 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))); 
    }; 
    }; 
} 

然后你可以使用它在你的代码如下所示:

$(document).mouseup((function(){ 
    this.easeDragging(); 
}).bind(this)); 
+1

您也可以在这里使用'$ .proxy()',例如, '$ .proxy(function(){this.easeDragging();},this)':) – 2010-08-19 19:28:56

+0

@Nick:一个非常有用的jQuery函数,我不知道,谢谢:-) – 2010-08-19 19:32:39

+0

优秀的答案,我学到了一些东西新的每一天! – Totomobile 2010-08-19 20:51:01

2

你在做什么就好(完全正确)。

一个优化技巧虽然,有没有必要,因为它已经是一个jQuery对象重新包装它,你可以这样做:

myPanorama.easeDragging(); 
0

无法绑定到文档中的第一位置(内插件),然后解决事件是否对你有用(发生在你的元素上,或者元素的子元素上)。

如果您要绑定到文档,例如,您应该使用命名空间。

$(document).bind('mouseup.panorama', function() { 
    ... 
} 
相关问题