2014-03-13 23 views
2

的“本”方面,我有这样一个侦听器:控制回调

this.frame.on('touchend', self.findClosestSlide); 

我需要把它这个样子,而不是一个匿名函数内部,以便以后能够解除绑定,使用函数名称。

我的问题是,一旦我在findClosestSlide函数中,我的this对象逻辑上变成this.frame

如何访问原始this,或者如何控制我发送到回调函数的上下文? (不使用匿名函数)

+0

'this.frame.on('touchend',self.findClosestSlide.bind(this));'? –

回答

2

您可以使用Function.bind()或$ .proxy(),以自定义上下文传递给回调像

跨浏览器,使用$.proxy()

this.frame.on('touchend', $.proxy(self.findClosestSlide, self)); 

IE9+,使用function.bind()

this.frame.on('touchend', self.findClosestSlide.bind(self)); 

为什么?因为默认情况下this里面的事件处理程序将引用事件所针对的元素

2

您可以存储this另一个变量如that$this不是用它你findClosestSlide函数内内。

+0

我使用了Arun的答案,而不是+1,因为它会起作用。谢谢:) –

+0

很高兴帮助!快乐编码bro :-) – Felix