我在使用我的类创建鼠标侦听器时遇到问题。首先我创建类(new mouseEventManager()),然后我调用init()函数,我想设置我的zoomHandler函数。它必须使用类'variable scale_level才能适当缩放屏幕。但是我被告知scale_level是NaN(不是数字)。
以下是代码:
function mouseEventManager() {
this.designManager;
this.canvasManager;
this.scale_level;
this.init = function(designManager, canvasManager) {
this.designManager = designManager;
this.canvasManager = canvasManager;
this.scale_level = 1; alert(this.scale_level);
var designManager = this.designManager;
//general mousemove listener
$(document).mousemove(function(e){
designManager.HAND_X = e.pageX;
designManager.HAND_Y = e.pageY;
});
//create scroll wheel listener
if(window.addEventListener) { document.addEventListener('DOMMouseScroll', this.zoomHandler, false); }
document.onmousewheel = this.zoomHandler;
}
this.zoomHandler = function() {
var delta = 0;
if (!event) event = window.event;
// normalize the delta
if (event.wheelDelta) {
// IE and Opera
delta = event.wheelDelta / 60;
} else if (event.detail) {
// W3C
delta = -event.detail / 2;
}
if (delta > 0) {
//scroll wheel up
this.scale_level = this.scale_level * 1.25; alert(this.scale_level);
this.canvasManager.mainLayer.setScale(this.scale_level);
this.canvasManager.mainLayer.draw();
} else if (delta < 0) {
//scroll wheel down
this.scale_level = this.scale_level * 0.8;
this.canvasManager.mainLayer.setScale(this.scale_level);
this.canvasManager.mainLayer.draw();
}
alert(delta);
}
}
看起来在zoomHandler中,没有定义mouseEventManager的内部成员。所以我认为我在变量范围或其他相关事情上做错了。
感谢您的帮助。
答案 0 :(得分:2)
问题是你的处理程序中的this
将不是实际调用处理程序时所需要的。
尝试按以下方式更改内容:
var manager = this;
this.zoomHandler = function() {
// ...
然后在函数中使用this
,而不是manager
,使用对象的“已保存”引用。
if (delta > 0) {
//scroll wheel up
manager.scale_level = this.scale_level * 1.25; alert(manager.scale_level);
manager.canvasManager.mainLayer.setScale(manager.scale_level);
manager.canvasManager.mainLayer.draw();
} else if (delta < 0) {
//scroll wheel down
manager.scale_level = manager.scale_level * 0.8;
manager.canvasManager.mainLayer.setScale(manager.scale_level);
manager.canvasManager.mainLayer.draw();
}