Leaflet.contextmenu回调 [英] Leaflet.contextmenu callbacks

查看:581
本文介绍了Leaflet.contextmenu回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Leaflet.contextmenu 库中遇到问题。

我遇到了很多不同的地图,保存在全局数组中。然后,我使用 contextmenu 选项在地图中添加了 contextmenu 。当我想定义回调函数时,我无法访问 arrMap [id] ,因为该函数不知道 id 我正在使用。

I got a number of different maps, saved in a global Array. Then I'm using the contextmenu options to have a contextmenu in my maps. When I want to define my callback functions, I can't access my arrMap[id], because the function doesn't know the id I'm using.

我的问题是:如何给对象( id )插入 Leaflet.contextmenu 库的回调函数?

My question here is: How can I give an object (the id, for example) into a callback function of the Leaflet.contextmenu library?

function x(){
    arrMap[id] = new L.map('map'+id,{
        contextmenu: true,
        contextmenuWidth: 140,
        contextmenuItems: [{
            text: 'Messung an dieser Position einfügen',
            callback: newMeasurement
        }, {
            text: 'zeige Koordinaten',
            callback: showCoordinates
        }, {
            text: 'Karte hier zentrieren',
            callback: centerMap
        }]
    });
}

function newMeasurement(e){
//do something with e AND ID
}

我想过类似的事情:

//function x(){...
callback: newMeasurement(e,id)
//...}

function newMeasurement(e,id){
  console.log(id);
}

...但这不起作用:(

...but that's not working :(

感谢大家的帮助!

推荐答案

您需要为所需的值创建一个闭包。

You need to create a closure over the value you want.

首先,阅读 «JS闭包如何工作?»问题。

然后,阅读关闭的MDN参考。然后,关于如何创建将不同值传递给每个处理程序函数的不同Leaflet事件处理程序的问题

首先阅读这些内容,尝试理解这个概念,我的意思是,如果您盲目地复制粘贴代码,那么stackoverflow之神将杀死一只小猫。

Read those first. Try to understand the concept. I mean it. If you blindly copy-paste code, then the gods of stackoverflow will kill a kitten.

现在,您想拥有一个事件处理函数,该函数将仅接收一个参数,例如

Now, you want to have an event handler function, which will receive just one parameter, like

function newMeasurement(ev){
    // do something with 'ev' AND 'id'
}

该函数需要接收一个参数,并且需要在某处具有 id 变量。好的,让我们创建一个返回函数的函数:

That function needs to receive one parameter, and needs to have an id variable somewhere. OK then, let's create a function that returns a function:

function getMeasurementHandler(id) {
    return function(ev) {
        doSomething(ev, id);
    }
}

那样,如果您运行例如:

That way, if you run e.g.:

var handlerForId1234 = getMeasurementHandler(1234);

这大致等于

var handlerForId1234 = function(ev) { doSomething(ev, 1234); }

让我们把它们放在一起:

Let's put it all together:

for (var id=0; id<4; id++) {
    arrMap[id] = new L.map('map'+id, {
        contextmenuItems: [{
            text: 'Somethingsomething',
            callback: getEventHandlerForId(id)
        }]
    });
}

getCallbackFuncForId(id) {
    return function(ev) {
        console.log('Event ', ev, ' in ID ', id);
    }
}

这篇关于Leaflet.contextmenu回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆