鼠标事件监听器& “这个”
我现在尝试在画布元素上注册鼠标事件侦听器。
当我的 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.updateCooperatives' 的结果不是函数”。之前的讨论告诉我,引用“this”丢失了,最终被绑定到(在本例中)Canvas 项目上。
所以我正在寻找一种像在java中那样调用“btnDown”的方法,这意味着它作为对象的一部分执行,因此可以访问该对象的变量。
我发现的唯一解决方案是单例...不好:(我确信有一个干净的解决方案... 请帮忙:-)
谢谢! J。
I'm now trying to register a mouse event listener on a canvas element.
As my JS application object initializes, it binds mouse events to a custom "MouseController" class:
this.canvas.addEventListener('mousedown',this.input0.btnDown, false);
"this" is the application object being initialized and canvas is a reference to the basic HTML5 canvas on my page.
The controller is a simple class like:
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
}
As the mouse is clicked, the console logs "result of expression this.updateCoordinates' is not a function". A previous discussion taught me about the reference "this" being lost, ending up being bound to, in this case, the Canvas item.
So I'm looking for a way to call "btnDown" like I would in java, meaning that it executes as part of an object and thus has access to the variables of that object.
The only solution I found was a singleton... No good :( I'm sure there's a clean solution...
Please help :-)
Thanks!
J.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建一个闭包:
或使用 ECMAScript 5 的
.bind()< /code> [MDN]
:
另请注意,您的其他方法称为
updateHIDCooperatives
,而不是更新坐标
。Either create a closure:
or use ECMAScript 5's
.bind()
[MDN]:Also note that your other method is called
updateHIDCoordinates
, notupdateCoordinates
.