javascript 你如何使用leaflet.js 中的.off() 事件方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10324857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:28:19  来源:igfitidea点击:

How do you use the .off() event method in leaflet.js?

javascriptgeocodingleaflet

提问by Spencer Cooley

I am trying to build a map application using leaflet.js and I can not figure out how to use the .off method. The documentation doesn't have any examples and I can't seem to find anything anywhere else online. I have distilled the problem into a more simple chunk of code so my question could be more clear.

我正在尝试使用 Leaflet.js 构建地图应用程序,但我不知道如何使用 .off 方法。该文档没有任何示例,我似乎无法在网上的其他任何地方找到任何内容。我已经将问题提炼成一个更简单的代码块,这样我的问题就可以更清楚了。

Basically I have it set up so that when you click the 'enable click' link it will add an event listener that adds a marker to the map every time you click it. I want to remove that event listener when you click 'disable click'.

基本上我已经设置好了,当你点击“启用点击”链接时,它会添加一个事件侦听器,每次你点击它时都会向地图添加一个标记。当您单击“禁用单击”时,我想删除该事件侦听器。

Here is a link to the demo

这是演示的链接

Here is the code I have now.

这是我现在拥有的代码。

$(document).ready(function(){

var map, cloudmade, sanAntonio, polygonPoints  


 map = new L.Map('map');
 cloudmade = new L.TileLayer('http://{s}.tile.cloudmade.com/d4334cd6077140e3b92ccfae2b363070/997/256/{z}/{x}/{y}.png', {
    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery ? <a href="http://cloudmade.com">CloudMade</a>',
    maxZoom: 18
});


 sanAntonio = new L.LatLng(29.4238889, -98.4933333); // geographical point (longitude and latitude)


 map.setView(sanAntonio, 13).addLayer(cloudmade);

//everything above sets up the map



function enableClick(){
  map.on('click', function(e) {    
    var marker = new L.Marker(e.latlng, {draggable:true});
    map.addLayer(marker);
  });//closes the click function

  this.disableClick = function(){
    map.off('click');
  }

}



//when 
$('#enable_click').click(function(){
  var enable_click = new enableClick()

  $('#disable_click').click(function(){
    enable_click.disableClick;
  });

});




});//closes the document ready function

I have already tried a bunch of different things so the whole 'this.disableClick' thing is just the latest strange thing I have tried. Anyone have a clue?

我已经尝试了很多不同的东西,所以整个 'this.disableClick' 东西只是我尝试过的最新奇怪的东西。有人有线索吗?

回答by Mourner

You need to pass the function to onand offby reference:

您需要将函数传递给onoff通过引用:

function doStuff() { ... }

map.on('click', doStuff);
...
map.off('click', doStuff);