How to remove a listener in OpenLayers 3

I make a copy of my question here on stackoverflow, because in gis.stackexchange all my questions do not attract any attention - many times I could not get an answer to simple questions. So now my question is how to remove the listener defined this way:

map.getViewport().addEventListener('click', function (e){
   console.log("clicked");      
}); 
+4
source share
2 answers

OL3 allows you to use your own kind of events that you could use instead, and to answer your initial question, provides an easy and quick way to unregister them.

Have a look at this example: http://openlayers.org/en/v3.13.0/examples/vector-layer.html

, :

  map.on('pointermove', function(evt) {
    if (evt.dragging) {
      return;
    }
    var pixel = map.getEventPixel(evt.originalEvent);
    displayFeatureInfo(pixel);
  });

  map.on('click', function(evt) {
    displayFeatureInfo(evt.pixel);
  });

ol.Map on, ol3. . . : http://openlayers.org/en/v3.13.0/apidoc/ol.MapBrowserEvent.html

, :

a) un, . :

  var callback = function(evt) {
    displayFeatureInfo(evt.pixel);
  };
  map.on('click', callback);
  map.un('click', callback);

b) ol.Observable.unByKey, . on once, , . :

  var key = map.on('click', function(evt) {
    displayFeatureInfo(evt.pixel);
  });
  ol.Observable.unByKey(key);

b), , . , unByKey, . , .

+12

, , , removeEventListener

function myFunction(event){
   //some stuff 
   console.log("clicked");   
}

map.getViewport().addEventListener('click',myFunction);

map.getViewport().removeEventListener('click',myFunction);

function myfunction(e) {
  alert("event click");
}


document.getElementById("mybtn").addEventListener("click",myfunction);



document.getElementById("mybtn2").addEventListener("click",function(e){
   document.getElementById("mybtn").removeEventListener("click",myfunction);
});
<button id="mybtn">btn</button><br/>
<button id="mybtn2" >remove btn click</button>
Hide result
+1

Source: https://habr.com/ru/post/1626000/


All Articles