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

Spe*_*ley 13 javascript geocoding leaflet

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

基本上我已将其设置为当您单击"启用单击"链接时,它将添加一个事件侦听器,每次单击它时都会向地图添加标记.我想在您点击"禁用点击"时删除该事件监听器.

这是演示的链接

这是我现在的代码.

$(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
Run Code Online (Sandbox Code Playgroud)

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

Mou*_*ner 26

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

function doStuff() { ... }

map.on('click', doStuff);
...
map.off('click', doStuff);
Run Code Online (Sandbox Code Playgroud)

  • 没有必要了.现在.off("click")将删除"click"事件的所有侦听器.(版本1.3.0 - > https://leafletjs.com/reference-1.3.0.html) (4认同)
  • 使用关闭时功能是否仍然需要? (2认同)