I have the following problem in event handlers in Javascript. I’ve got an object that has a mousemove event handler like so:
function MyObject(){ }
function MyObject.prototype = {
currentMousePosition: null,
onMouseMove: function(ev){
this.currentMousePosition = this.getCoordinates(ev);
},
getCoordinates: function(ev){
if (ev.pageX || ev.pageY)
return { x: ev.pageX, y: ev.pageY };
return { x: ev.clientX + document.body.scrollLeft - document.body.clientLeft, y: ev.clientY + document.body.scrollTop - document.body.clientTop };
}
};
The problem I’m trying to solve resolves around object context. Within my onMouseMove function it assigns the currentMousePosition property. Naturally this won’t work because it’s a static function handling the mousemove event.
What I’m looking for is a technique/method to pass an object context in with my event handler. The best example that I can think of is the Google Maps API function GEvent.bind().
With it you can pass the object with the function you want to fire on the specified event. I’m essentially looking for the same thing.
Today, many people do this with an explicit closure:
But in the future, you’ll do it with the ECMAScript Fifth Edition method
function.bind:(Any further arguments passed to
function.bindare prepended to the argument list of the target function when called.)Until browsers all support
function.bindnatively, you can hack support in yourself using prototypes and closures. See the bottom of this answer for an example implementation.It’s only
document.bodyif you are in IE Quirks Mode. You don’t want to be in Quirks Mode. With a Standards Mode doctype, it’sdocument.documentElementinstead. So if you need to support different pages that might use either of the modes, or you still need to support IE5 for some reason (let’s hope not):