[GIS] How to unlisten an event in OpenLayers 4

eventsjavascriptopenlayers

I am trying to suppress the single click event that adds popups to the map. I have the following function:

function addFullScreenPopups(){
      map.on('singleclick', function(evt) {
        var popup = new ol.Overlay.Popup({insertFirst: false});
        map.addOverlay(popup);
        var prettyCoord = ol.coordinate.toStringHDMS(ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326'), 2);
        console.log("Pretty Coordinates : "+prettyCoord);
        popup.show(evt.coordinate, '<div><h2>Coordinates</h2><p>' + prettyCoord + '</p></div>');
    });
    }

I used to use unByKey to unlisten the single click event. However, the developers removed this method in OpenLayers 4. Therefore, I am bound to use map.un method. I am trying to use this method, but it is not doing anything. I am doing map.un("singleclick", addFullScreenPopups()); for unlistening this event, but it is not doing anything. Why?

Update: I also looked at the signature of .on method and it is given as on(type, listener, opt_this). So I changed my .on method to map.on('singleclick', function addFullScreenPopups(evt) {//statements}); and called map.un('singleclick', addFullScreenPopups()); Unfortunately, this didn't help me out.

Best Answer

Try to wrap your callback function in a separate function. Something like that:

//here is you callback function
function myCallback(evt){
        var popup = new ol.Overlay.Popup({insertFirst: false});
        map.addOverlay(popup);
        var prettyCoord = ol.coordinate.toStringHDMS(ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326'), 2);
        console.log("Pretty Coordinates : "+prettyCoord);
        popup.show(evt.coordinate, '<div><h2>Coordinates</h2><p>' + prettyCoord + '</p></div>');
}
//To bind the event 
map.on('singleclick', myCallback);
//To unbind the event
map.un('singleclick', myCallback);