I'm attempting to create a basic wrapper for mouse behavior. Here is the current code I have:
function MouseWrapper() {
this.mouseState = 0;
this.OnMouseDownEvent = null;
this.OnMouseUpEvent = null;
document.body.onmousedown = this.OnMouseDown.bind(this);
document.body.onmouseup = this.OnMouseUp.bind(this);
}
MouseWrapper.prototype.Subscribe = function (eventName, fn) {
// Subscribe a function to the event
if (eventName === 'MouseDown') {
this.OnMouseDownEvent = fn;
} else if (eventName === 'MouseUp') {
this.OnMouseUpEvent = fn;
} else {
alert('Subscribe: Unknown event.');
}
}
MouseWrapper.prototype.OnMouseDown = function () {
this.mouseState = 1;
// Fire event
$.dump(this.OnMouseDownEvent);
if (this.OnMouseDownEvent !== null) {
alert('test');
this.OnMouseDownEvent();
}
}
MouseWrapper.prototype.OnMouseUp = function () {
this.mouseState = 0;
// Fire event
if (this.OnMouseUpEvent !== null) {
this.OnMouseUpEvent();
}
}
After some investigation, it appears that in MouseWrapper.prototype.OnMouseUp
and
MouseWrapper.prototype.OnMouseDown
, the keyword "this" does not refer to the current instance of MouseWrapper
. It makes sense why it doesn't point to my instance, but how can this issue be addressed?
I am looking for a proper solution to this problem without resorting to any hacks.
My thought process: * Implement a singleton pattern (since there's only one mouse) * Find a way to pass my instance to OnMouseDown/Up - any suggestions on how to achieve this?
Thank you in advance for your assistance!