问题描述
我对我的问题进行了副本在这里是stackoverflow的原因,因为在gis.stackexchange上,我所有的问题都没有引起任何关注-很多时候,我无法在那里找到简单问题的答案.因此,我现在的问题是如何删除以这种方式定义的侦听器:
I make a copy of my question here at stackoverflow, because at gis.stackexchange all my questions do not attract any attention - many times I could not get an answer to simple questions there. So, my question now is how to delete a listener defined this way:
map.getViewport().addEventListener('click', function (e){
console.log("clicked");
});
推荐答案
OL3发出了自己可以使用的事件类型,并且为了回答您的原始问题,它提供了一种简单快速的方法来注销它们.
OL3 emmits its own kind of events you could use instead and, to answer your original question, gives an easy and quick way to unregister them.
请看以下示例: http://openlayers.org/zh/v3.13.0/examples/vector-layer.html
更具体地说,在以下几行:
More specifically, at these lines:
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
The ol.Map
object has a on
method you can use to register event listeners on the ol3 map browser events. It's best to use those events instead of standard browser events. See the list of all map browser events here: http://openlayers.org/en/v3.13.0/apidoc/ol.MapBrowserEvent.html
要取消注册,您可以:
a)使用un
方法,但请确保为提供与第二个参数相同的回调方法.换句话说:
a) use the un
method, but make sure you to give the same callback method as 2nd argument. In other words:
var callback = function(evt) {
displayFeatureInfo(evt.pixel);
};
map.on('click', callback);
map.un('click', callback);
b)另一种方法是使用我非常喜欢的ol.Observable.unByKey
方法.调用on
或once
时,它将返回引用该事件的键.然后,您可以使用该键取消监听您的活动:
b) an other way is to use the ol.Observable.unByKey
method, which I like a lot. When calling on
or once
, it returns a key that references the event. You can then use that key to unlisten your event:
var key = map.on('click', function(evt) {
displayFeatureInfo(evt.pixel);
});
ol.Observable.unByKey(key);
我发现b)更加友好,因为您可以注册一堆事件侦听器并将所有键放在数组中.如果要全部注销,请在数组中循环并调用unByKey方法,然后清空数组.与不必手动注销所有事件相比,这种方式生成的代码更少.
I find b) to be more friendly as you can register a bunch of event listeners and put all the keys inside an array. When you want to unregister them all, loop in the array and call the unByKey method, then empty the array. It generates less code that way than having to unregister all events manually.
这篇关于如何在OpenLayers 3中删除侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!