Leaflet.contextmenu callbacks

后端 未结 1 1352
不思量自难忘°
不思量自难忘° 2021-01-28 07:59

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 cont

相关标签:
1条回答
  • 2021-01-28 08:38

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题