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.
Either create a closure:
or use ECMAScript 5’s
.bind()[MDN]:Also note that your other method is called
updateHIDCoordinates, notupdateCoordinates.