vdegenne
vdegenne

Reputation: 13308

referring to the object in a callback function in javascript

My instruction is as :

map.canvas.addEventListener("mousemove", mapOnMouseMove, false);

function mapOnMouseMove (e) {
   // here : this refers to the canvas of the map object
   // i want to refer to the map (is there a way ?)
}

Upvotes: 0

Views: 65

Answers (2)

Florent
Florent

Reputation: 12420

You could trick this to refer to map like this:

map.canvas.addEventListener("mousemove", canvasOnMouseMove, false);

function canvasOnMouseMove (e) {
   mapOnMouseMove.call(map, e);
}

function mapOnMouseMove (e) {
   // here : this refers to the map object
}

Upvotes: 1

James Allardice
James Allardice

Reputation: 166061

You can use bind to create a bound function (where the value of this is your map object):

map.canvas.addEventListener("mousemove", mapOnMouseMove.bind(map), false);

But note that since bind is an ES5 method, it's not supported in older browsers. The MDN article linked to above provides a polyfill that you will probably want to use as well.

Upvotes: 0

Related Questions