2012-05-12 56 views
0

我不明白爲什麼這種情況正在發生的兩種不同的方式看到預期的結果...JavaScript對象,使用電話功能

我需要得到它在鼠標按下設置的對象startPoint和當前e.pageY從mousemove做一些計算。

var adjustHeight = { 
    change: function(e) { 
     console.log(this.startPoint) 
     console.log(e.pageY); 
    }, 
}; 

$('#dragger').mousedown(function(e) { 
    e.preventDefault(); 

    adjustHeight.startPoint = e.pageY; 

    $(window).on('mousemove', adjustHeight.change()); 

    $(window).on('mouseup', function() { 
     $(window).off('mousemove', adjustHeight.change()) 
    }); 
}) 

但是控制檯打印出的對象startPoint這是我所期望的,但e.pageY未定義

但是當我使用這條線,而不是

... 
    $(window).on('mousemove', adjustHeight.change); 

    $(window).on('mouseup', function() { 
     $(window).off('mousemove', adjustHeight.change) 
    }); 
... 

我得到的e.pageY如預期,但現在startPoint未定義。當我檢查什麼this指向它是DOMWindow ....

我的問題是爲什麼會發生這種情況,我將如何去同時獲取兩個對象屬性和功能e

回答

2
$(window).on('mousemove', adjustHeight.change()); 

被立即執行adjustHeight.change返回值傳遞給.on()。由於您未傳遞任何參數至adjustHeight.change,因此e將爲undefined(並且e.pageY將不可用)。


$(window).on('mousemove', adjustHeight.change); 

正確傳遞函數.on,因此後來的事件對象傳遞給處理程序,您可以訪問e.pageY。但上下文(this)不再是adjustHeight,它是您綁定處理程序的DOM元素。在這種情況下,windowwindow沒有startPoint屬性。

MDN文檔有an excellent article about this(一般),as does quirksmode.org(關於事件處理程序)。


傳遞一個新的功能的處理程序,它調用adjustHeight.change並傳遞event對象:使用$.proxy[docs]adjustHeight.changeadjustHeight

$(window).on('mousemove', function(event) { 
    adjustHeight.change(event); 
}); 

綁定:

$(window).on('mousemove', $.proxy(adjustHeight.change, adjustHeight)); 

由於您還想稍後解除綁定處理程序,因此應將其分配給變量或使用namespaced event [docs]

舉例:

所有的
$(window).on('mousemove.dragger', $.proxy(adjustHeight.change, adjustHeight)); 

$(window).on('mouseup.dragger', function() { 
    // removes both, the mousemove and mousup event handlers 
    $(window).off('.dragger'); 
}); 
0

首先,這是錯誤的:

$(window).on('mousemove', adjustHeight.change()); 

然後,change()默認情況下不必然adjustHeight。你必須做一些事情,如:

$(window).on('mousemove', function() { 
    adjustHeight.change(); 
}); 

或者,在現代瀏覽器:

$(window).on('mousemove', adjustHeight.change.bind(adjustHeight)); 
0

...

$(window).on('mousemove', adjustHeight.change); 

$(window).on('mouseup', function() { 
    $(window).off('mousemove', adjustHeight.change) 
}); 

...

(行:3 )

console.log("start:" + adjustHeight.startPoint)