mapboxmapbox-gl-js

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

  • 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.