Leaflet.contextmenu callbacks

时光总嘲笑我的痴心妄想 提交于 2019-12-11 16:52:37

问题


I'm struggling with a problem in the Leaflet.contextmenu library.

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.

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
}

I thought about something like:

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

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

...but that's not working :(

Thanks everybody for the help!


回答1:


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

First, read the «How do JS closures work?» question.

Then, read the MDN reference for closures. And then, this question about how to create different Leaflet event handlers passing a different value to each handler function


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'
}

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);

That is more-or-less equivalent to

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);
    }
}


来源:https://stackoverflow.com/questions/40657245/leaflet-contextmenu-callbacks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!