I know that there are no classes in Javascript, I refer to constructor functions as to classes for convenience.
I’m making a class called InputHandler in Javascript. It has a method called onMouseDown, and it registers it as an event handler like this:
Irenic.InputHandler.prototype.attach = function()
{
var inputHandler = this; //Get the instance of InputHandler
document.addEventListener("keydown", inputHandler.onKeyDown, false); //Concentrate on this, but the question applies to all of these.
document.addEventListener("keyup", inputHandler.onKeyUp, false);
document.addEventListener("mousemove", inputHandler.onMouseMove, false);
document.addEventListener("mouseup", inputHandler.onMouseUp, false);
document.addEventListener("mousedown", inputHandler.onMouseDown, false);
}
(Irenic is the name of the engine I’m building, it is also a global object which has all these classes.)
The inputHandler.onMouseDown method looks like this:
Irenic.InputHandler.prototype.onMouseDown = function(event)
{
var inputHandler = this; //This sadly refers to the document, not an instance of InputHandler
console.log(inputHandler); //Logs #document
if (event.button == 0)
{
inputHandler.mouse.lmb = true;
}
if (event.button == 1)
{
inputHandler.mouse.wheel = true;
}
if (event.button == 2)
{
inputHandler.mouse.rmb = true;
}
}
As I’ve said in the comments, the this keyword refers to the element the event fired on. I obviously don’t want that: so how do I make it refer to an instance of InputLoader?
In your constructor, bind the instance’s methods to that instance:
This way the instance is ready to go as soon as it is constructed.
See
Function#bind