我有一个简单的问题难倒了我:
在 Leaflet 应用程序中,我有一个用于单击 map 上的元素的事件监听器:
marker.on('click', function () {
doStuff();
$('element').doStuff();
setView(this.getLatLng());
});
但是,setView 方法还会触发“ map 移动”事件,我不想触发该事件。使用纯 JavaScript 或 jQuery,我可以防止在单击事件函数内触发任何其他事件吗?
编辑:现在用 fiddle !要使用它,只需单击 map 上的任意位置即可。正如您所看到的,e.stopPropagation() 在放置在点击事件监听器中时不起作用。
最佳答案
我不相信你可以阻止 moveend
被解雇。 (注意:这些不是 jQuery 事件 - Leaflet 有自己的内部事件系统。)这是 setView
的来源:
setView: function (center, zoom) {
zoom = zoom === undefined ? this.getZoom() : zoom;
this._resetView(L.latLng(center), this._limitZoom(zoom));
return this;
}
_resetView
总是在最后触发 moveend
:
_resetView: function (center, zoom, preserveMapOffset, afterZoomAnim) {
var zoomChanged = (this._zoom !== zoom);
if (!afterZoomAnim) {
this.fire('movestart');
if (zoomChanged) {
this.fire('zoomstart');
}
}
...
this.fire('moveend', {hard: !preserveMapOffset});
}
您可以研究自定义这些函数以允许抑制事件。
更新:
或者,您可以更改 moveend
事件处理程序。让它跟踪一个标志,当您不希望发生正常操作时设置该标志。
例如,您将设置类似于以下内容的处理程序:
map.on('moveend', myHandler);
让 myHandler
执行以下操作:
function myHandler(e) {
if (stopFlag) {
return;
}
else {
// Normal operation
...
}
}
然后只需启用和禁用 stopFlag
即可控制流量。这样做的优点是您不必随应用程序一起发布 Leaflet 的自定义版本。
关于javascript - 防止在 setView 之后在 Leaflet 中触发 moveend 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28188743/