問題描述
我正在努力解決 Leaflet.contextmenu
庫中的問題.
I'm struggling with a problem in the Leaflet.contextmenu
library.
我有許多不同的地圖,保存在一個全局?jǐn)?shù)組中.然后我使用 contextmenu
選項在我的地圖中有一個 contextmenu
.當(dāng)我想定義我的回調(diào)函數(shù)時,我無法訪問我的 arrMap[id]
,因為該函數(shù)不知道我正在使用的 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
庫的回調(diào)函數(shù)中?
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 :(
感謝大家的幫助!
推薦答案
你需要為你想要的值創(chuàng)建一個閉包.
You need to create a closure over the value you want.
首先,閱讀 ?JS 閉包如何工作?? 問題.
然后,閱讀 MDN 閉包參考.然后,this question about how to create different Leaflet event handlers pass每個處理函數(shù)的值不同
首先閱讀這些內(nèi)容.嘗試?yán)斫膺@個概念.我是認(rèn)真的.如果你一味地復(fù)制粘貼代碼,那么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.
現(xiàn)在,你想要一個事件處理函數(shù),它只接收一個參數(shù),比如
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'
}
那個函數(shù)需要接收一個參數(shù),并且需要在某處有一個id
變量.好的,那么,讓我們創(chuàng)建一個返回函數(shù)的函數(shù):
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);
}
}
這篇關(guān)于Leaflet.contextmenu 回調(diào)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!