Reputation: 815
I am having difficulty understanding how to stop an event listener for my map after I set it. There are two other similar questions here but after effort I cannot get this to work for me.
My code to set the event listener is simple :
map.on("move", function() {
console.log("foo");
}
})
How can I stop this at will? I have tried map.off('move');
but this does not work for me. I have also looked at the documentation at the mapbox docs but no luck there either.
The documentation shows that I need both :
But, I don't know what I should be using as listener. (This is why I could only try map.off('move');
).
How do I set .off() properly in this instance?
Upvotes: 1
Views: 1628
Reputation: 1178
As with the accepted answer, you do need to use a static or arrow function variable to be able to remove the event listener later. We use a remove function along with an array of event names and related functions.
map.on("mousemove", singleSelect);
// Add to queue for later removal
window.mapEventListeners.push({eventName: "mousemove", functionName: singleSelect});
Removal function:
function removeCurrentMapEventListeners() {
window.mapEventListeners.forEach((listenerInfo) => {
districtingMap.off(listenerInfo.eventName, listenerInfo.functionName);
});
// reset
window.mapEventListeners = [];
// Also for DOM event listeners
window.removeEventListener("keydown", handleAltKeyDown);
}
Upvotes: 0
Reputation: 126045
Use it like this:
const myfunc = () => console.log('foo');
map.on('move', myfunc);
map.off('move', myfunc);
You need to use either a static function or assign the arrow function to a variable in order to by able to call off
with the exact same function.
Upvotes: 3