views:

2078

answers:

2

How do I remove the 'bounds_changed' Event listener in Google Maps API v3?

google.maps.event.removeListener(_???_);
+1  A: 

addListener returns a handle which you can later pass to removeListener:

var listenerHandle = google.maps.event.addListener(map, 'bounds_changed', function() {

google.maps.event.removeListener(listenerHandle);
Andrew
So there is no longer static variables for the listeners?
mp_
Listeners need to be removed one by one. You can't unbind them all ala jQuery. I know because I thought the same and got confused on this point too. I eventually worked it out and the pseudo-code above roughly illustrates how I did it.
Andrew
Look at my answer, I think it's a better solution.
Maiku Mori
Drat! Yours *is* a better answer.
Andrew
Where is this documented? I can't seem to find it.
Drew LeSueur
+8  A: 

Usually you can find answers to such questions in Google Maps API documentation.

As Andrew said, addListener returns a handle which you can use later to remove the listener. That's because a single event can have many listeners and to remove them you must save a reference to each of attached listeners.

There's also a function which removes all of the listeners at the same time:

clearListeners(instance:Object, eventName:string);
//In your case:
google.maps.event.clearListeners(map, 'bounds_changed');

Here's the Google Maps API reference where you can read about it.

Maiku Mori
So will this remove ONLY the bounds_changed event?
mp_
What's the pro/con of using this method vs Andrews method?
mp_
This removes all listeners from the bounds_changed event. While Andrew's method removes one. If you don't want to store the handle somewhere and you only have to worry about 1 listener for given event then this is the way to go.
Maiku Mori
As I said events can have many listeners, but it seems like you're just using 1 in your code. If you'll understand that concept you will see the different uses for both functions. Also see the link I provided, it has nice explanations for both of those functions.
Maiku Mori