开发者

Mouse event listener & "this"

开发者 https://www.devze.com 2023-04-12 08:26 出处:网络
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:

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,开发者_StackOverflow中文版 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.


Either create a closure:

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

or use ECMAScript 5's .bind() [MDN]:

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

Also note that your other method is called updateHIDCoordinates, not updateCoordinates.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号