0

我在使用我的类创建鼠标侦听器时遇到问题。首先,我创建类(new mouseEventManager()),然后调用 init() 函数,我想设置我的 zoomHandler 函数。它必须使用类的变量 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 的内部成员。所以我认为我在变量范围或相关方面做错了。

感谢您的任何帮助。

4

1 回答 1

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();
}
于 2012-06-20T04:05:19.913 回答