Removing Event Listeners

2,518 views
Skip to first unread message

Elliott

unread,
Feb 1, 2012, 10:28:56 AM2/1/12
to leafl...@googlegroups.com
Hi all,

What is the best way to 'manage' my event listeners?

map.off('click', newWaypoint); //remove previous event listener - works fine
map.on('click', function(e){ //add my new event listener, define the function - works fine

 //do some stuff here, specifically add a marker when user clicks
 
//to stop them adding more markers, i want to go back, 
//remove this event listener, add the 'newWaypoint' one again.

map.off('click'); //can we remove all click event listeners from the map? This is the crux.
map.on('click', newWaypoint); //this line works and is not a problem
});

Pointers would be appreciated.

Cheers,
Elliott

Vladimir Agafonkin

unread,
Feb 1, 2012, 11:15:43 AM2/1/12
to leafl...@googlegroups.com
Hi Elliott,

It is best to allways name your callbacks or store them in a variable so you could remove them in code. If you need to use an anonymous function which you remove inside itself, you can do it like this:

map.on('click', function myCallback(e) {
   ...
   map.off('click', myCallback);
});

2012/2/1 Elliott <elliott...@gmail.com>

Elliott

unread,
Feb 1, 2012, 12:49:55 PM2/1/12
to leafl...@googlegroups.com
Thank you!
Reply all
Reply to author
Forward
0 new messages