鼠标事件监听器& “这个”

时间:2011-10-11 08:03:53

标签: javascript oop canvas mouseevent

我现在正尝试在canvas元素上注册一个鼠标事件监听器。

当我的JS应用程序对象初始化时,它将鼠标事件绑定到自定义的“MouseController”类:

this.canvas.addEventListener('mousedown',this.input0.btnDown, false);

“this”是正在初始化的应用程序对象,canvas是对我页面上基本HTML5画布的引用。

控制器是一个简单的类,如:

function MouseController(eventHandler) {
this.handler = eventHandler;

this.contact = false;

this.coordX = 0;
this.coordY = 0;
}

MouseController.prototype.btnDown = function(event) {
// Faulty line ???
this.updateCoordinates(event);
}

MouseController.prototype.updateHIDCoordinates = function (event) {
// code to set coordX and coordY of the controller instance
// Again, I can't access the object from here as "this" refers to the Canvas
}

单击鼠标时,控制台会记录“表达式结果this.updateCoordinates'不是函数”。之前的讨论告诉我关于“this”被丢失的引用,最终被绑定到Canvas项目。

所以我正在寻找一种像在java中一样调用“btnDown”的方法,这意味着它作为对象的一部分执行,因此可以访问该对象的变量。

我找到的唯一解决方案是单身......不好:(我确定有一个干净的解决方案...... 请帮忙: - )

谢谢! 学家

1 个答案:

答案 0 :(得分:1)

创建一个闭包:

var controller = this.input0;
this.canvas.addEventListener('mousedown', function(event){
    controller.btnDown(event);
}, false);

或使用ECMAScript 5的.bind() [MDN]

this.canvas.addEventListener('mousedown', this.input0.btnDown.bind(this.input0), false);

另请注意,您的其他方法称为updateHIDCoordinates,而不是updateCoordinates