【问题标题】:Mouse event listener & "this"鼠标事件监听器和“this”
【发布时间】:2011-10-11 08:03:52
【问题描述】:

我现在正在尝试在画布元素上注册鼠标事件侦听器。

当我的 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”的方法,这意味着它作为对象的一部分执行,因此可以访问该对象的变量。

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

谢谢! J.

【问题讨论】:

    标签: javascript oop canvas mouseevent


    【解决方案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

    【讨论】:

    • 现在很奇怪,当我的 btnDown 被调用时,我将其命名为“this.handler.click()”。应用程序对象的“click()”方法简单调用:console.log('click at' + this.input0.coordX); input0 被设置为成员变量。从控制器回来,“handler.input0”设置为空......知道为什么吗?谢谢
    • 嗯,现在对 input0 的引用再次起作用了.. .wierd... 我当然在没有注意到的情况下破坏/修复了一些东西。感谢您的帮助!
    猜你喜欢
    • 2014-02-21
    • 1970-01-01
    • 2020-02-20
    • 2011-09-19
    • 2014-12-13
    • 2015-11-30
    • 2013-07-20
    • 2013-12-23
    • 1970-01-01
    相关资源
    最近更新 更多