0

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!

user2441511
  • 11,036
  • 3
  • 25
  • 50
pyysaw
  • 43
  • 7

1 Answers1

3

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);
    }
}
IvanSanchez
  • 18,272
  • 3
  • 30
  • 45
  • Wow, havent heard of these closures yet, pretty exited, that you can do things like this! thank you sir! – pyysaw Nov 17 '16 at 15:03