(Note, this is a rant in disguise, but I really would like a solution too)
I run into this problem quite a bit. Perhaps I’m just too used to the predictability of AS3, but there is often no easy way to avoid JavaScript (or other JavaScript developers) from butchering your this
value, and setting it to whatever it wants before calling a function. Most often I run into this issue setting callbacks for events.
At the moment, my code looks like this: https://gist.github.com/IQAndreas/10230280 (please excuse my messy prototype code)
Line 42 simply does not work just because this.hitBox doesn’t exist on the event listener target (but it does exist on my slider). This problem can be “solved” by manually feeding the slider in as “this” on the line where you add the event listener:
var theRealThis = this;
target.addEventListener(MouseEvent.MOUSE_DOWN, function(event) {
onMouseDown.call(theRealThis, event);
});
But this is horrible, and ugly, and there is no easy way to remove the event listener.
Am I writing my code wrong, or does working with JavaScript really require jumping through this many hoops?