'Stopping map.on() listener in Mapbox GL-JS

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 :

  1. Type (string) The event type to remove listeners for.
  2. Listener (Function) The listener function to remove.

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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Steve Bennett