Javascript – Attaching and Detaching events to/from Virtual Earth maps


I don't think this is particularly quirky, but in an attempt to control my JavaScript code (if it is possible to really control JavaScript 😉 ) I have been wrapping all of my client-side JavaScript in lovely objects. Or as lovely as I can make them anyway.

One of the first issues I came across was attaching events to anything from within these objects. It soon became apparent that this does not always mean what you think it means and as a result my code would have to look like this:

var obj = this;
_map.AttachEvent("onclick", function(event){ obj.onClickMap(event); });

That way all of the events call the current object. Jobs a good 'un.

However, when detaching events from the Virtual Earth map object you need to pass the function that you originally assigned so that only that is unassigned. This does not work:

_map.DetachEvent("onclick", function(event){ obj.onClickMap(event); });

…not that I ever really expected it to. But I can't work out just how to detach that event!

Best Solution

Well obviously you could store the function:

var obj = this;
var func = function(event){ obj.onClickMap(event); }
_map.AttachEvent("onclick", func);

And then detach:

_map.DetachEvent("onclick", func);

Does that help?

Related Question