javascript - Leaflet.contextmenu callbacks -
i'm struggling problem in leaflet.contextmenu
library.
i got number of different maps, saved in global array. i'm using contextmenu
options have contextmenu
in maps. when want define callback functions, can't access arrmap[id]
, because function doesn't know id
i'm using.
my question here is: how can give object (the id
, example) callback function of leaflet.contextmenu
library?
function x(){ arrmap[id] = new l.map('map'+id,{ contextmenu: true, contextmenuwidth: 140, contextmenuitems: [{ text: 'messung dieser position einfügen', callback: newmeasurement }, { text: 'zeige koordinaten', callback: showcoordinates }, { text: 'karte hier zentrieren', callback: centermap }] }); } function newmeasurement(e){ //do e , id }
i thought like:
//function x(){... callback: newmeasurement(e,id) //...} function newmeasurement(e,id){ console.log(id); }
...but that's not working :(
thanks help!
you need create closure on value want.
first, read «how js closures work?» question.
then, read mdn reference closures. , then, this question how create different leaflet event handlers passing different value each handler function
read first. try understand concept. mean it. if blindly copy-paste code, gods of stackoverflow kill kitten.
now, want have event handler function, receive 1 parameter, like
function newmeasurement(ev){ // 'ev' , 'id' }
that function needs receive 1 parameter, , needs have id
variable somewhere. ok then, let's create function returns function:
function getmeasurementhandler(id) { return function(ev) { dosomething(ev, id); } }
that way, if run e.g.:
var handlerforid1234 = getmeasurementhandler(1234);
that more-or-less equivalent to
var handlerforid1234 = function(ev) { dosomething(ev, 1234); }
let's put 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); } }
Comments
Post a Comment