views:

235

answers:

2

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(){ }
functino 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.

+3  A: 

Today, many people do this with an explicit closure:

var myobject= new MyObject();
element.onmousemove= function() {
    myobject.onMouseMove();
};

But in the future, you'll do it with the ECMAScript Fifth Edition method function.bind:

element.onmousemove= myobject.onMouseMove.bind(myobject);

(Any further arguments passed to function.bind are prepended to the argument list of the target function when called.)

Until browsers all support function.bind natively, you can hack support in yourself using prototypes and closures. See the bottom of this answer for an example implementation.

document.body.scrollLeft

It's only document.body if you are in IE Quirks Mode. You don't want to be in Quirks Mode. With a Standards Mode doctype, it's document.documentElement instead. 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):

var viewport= document.compatMode==='CSS1Compat'? document.documentElement : document.body;
return {x: ev.clientX+viewport.scrollLeft, y: ev.clientY+viewport.scrollTop};
bobince
This is a great start, thank you!
Matt
A: 

You need to pass a wrapper function that calls your handler on the correct context.

For example:

addHandler(function(ev) { someObject.onMouseMove(ev); });
SLaks