Domanda

I am using Decarta JS API PIN event handler

I am displaying pins on a map and the click event for each pin is fired correctly. The trouble comes in when I try pass the pin id to the handler. It ALWAYS displays the last id loaded regardless of which pin is clicked on. My code for declaring the listener is:

for (var idx = 0; idx < jsonObjects.devices.length; idx++) {
    var device = jsonObjects.devices[idx]
    deCarta.Core.EventManager.listen('click', function() {home.pinPushed(device.id);}, device.pin);
}

This is done in a loop through all the locations I am displaying. They are displayed correctly at their respective coordinates, and logging the previous line clearly shows that each pin is declared with the correct id. However, whenever I click on a pin, the LAST id declared is the only id ever passed to the handler:

home.pinPushed(device.id)

How do I get each pin to pass the unique id when the pin is clicked?

È stato utile?

Soluzione

Try this :

deCarta.Core.EventManager.listen('click', 
 (function(id) { return  function (){home.pinPushed(id);}})(device.id), device.pin);

Beautify version :

 deCarta.Core.EventManager.listen('click', (function (id)
 {
     return function ()
     {
         home.pinPushed(id); //<---- id here is the closured variable
     }
 })(device.id), device.pin);

Explanation :

Js has a function scope ( not braces ({}) scope.)

Your for loop is not creating ANY scope/function.

What I was doing is to create execution context for each iteration.

for each iteration im sending the current device.id to a function which in turn , returns another function which closured the variable.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top