2012-01-16 39 views
2
this.progress.click(function(e) { // works 
    var seek = (e.pageX - this.offsetLeft)/$(this).width(); 
    self_ref[index].seek(seek * self_ref[index].source.duration); 
}); 

this.progress.click($.proxy(function(e) { // doesn't work 
    var seek = (e.pageX - this.offsetLeft)/$(this).width(); 
    this.seek(seek * this.source.duration); 
}, this)); 

this.offsetLeft在第一個示例中工作,但不在第二個示例中。我需要$.proxy,所以我不能擺脫它。一旦上下文在其功能中發生變化,我無法找到一種方法來讓this.offsetLeft工作。

PS:我不能再回到使用self_ref[index]因爲我正在處理的擴展。

回答

2

要麼保持this副本外的範圍,想丹尼斯說,或者使用e.currentTarget得到的DOM元素正在處理該事件。

this.progress.click($.proxy(function(e) { // doesn't work 
    var seek = (e.pageX - e.currentTarget.offsetLeft)/$(e.currentTarget).width(); 
    this.seek(seek * this.source.duration); 
}, this)); 

在你的第一個例子(非代理):this == e.currentTarget

+0

謝謝,這正是我所期待的。 – 2012-01-16 17:38:23

0

編輯:這兩個其他答案顯然要好得多。對於:-)


在第一工作例如,this一個DOMElement被點擊:this.progress

在第二示例中,使用$.proxy時,this指周圍的上下文,而不是progress元素了。

所以proxified處理內,你應該使用:

this.progress.get(0).offsetLeft 
// .get(0) is to obtain the DOMElement 
// and get access to the javascript property offsetLeft 

,而不是this.offsetLeft

+0

它不工作,我嘗試了幾種組合,以獲得左側。 'offsetLeft','offset()。left','left','.css('offset')。left'。 – 2012-01-16 17:23:36

+0

使用'this.progress.get(0).offsetLeft'來處理DOMElement(就像在第一個例子中是'this') – 2012-01-16 17:25:28

1

this在第一個例子中是指被點擊的元素。在第二個中,您正在使用它來引用被單擊的元素以及您正在代理該函數的對象。您可以通過重命名this當您創建的處理程序,並創建一個封閉修改原來,工作示例:

var self = this; 
this.progress.click(function(e) { 
    var seek = (e.pageX - this.offsetLeft)/$(this).width(); 
    self.seek(seek * self.source.duration); 
});