views:

204

answers:

2

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!

+1  A: 

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?

samjudson
Nice one...you must have entered that at the same time I did! Two independent answers which say the same thing is more than good enough for me. Thanks.
Jason
A: 

Aha! A sudden flash of inspiration led me to this solution (which may or may not be the best way, but it does work). When attaching the event I use this:

// Attach map events
var obj = this;
_currentOnClickMapHandler = function(event){ obj.onClickMap(event); };
_map.AttachEvent("onclick", _currentOnClickMapHandler);

where _currentOnClickMapHandler is a global in the class.

When I want to detach the event I use this:

if (_currentOnClickMapHandler)
{
    _map.DetachEvent("onclick", _currentOnClickMapHandler);
}

Seems to work, and the reason is fairly apparent to me as to why so I'm not too concerned about it as a solution. If anyone has a better idea (or agrees with this solution so I can feel more secure about it!) then please let me know.

Jason