1

I think the problem is really clear. This is my code:

 // Add markers for each spot
 for(var spot of spots) {

   var spotId: number = +spot.id;
   console.log(spotId);

   // Add marker for current spot
   L.marker([spot.latitude, spot.longitude], {icon: this.mapService.getSchoolIcon() })
     .addTo(this.map)
     .on('click', () => console.log('CLICKED: ' + spotId)  );
 }

And this is the output in the console if I click all pins:

1
2
3
4
CLICKED: 4
CLICKED: 4
CLICKED: 4
CLICKED: 4
rakete
  • 2,953
  • 11
  • 54
  • 108
  • If you are writing TypeScript, why not use `let`? https://www.typescriptlang.org/docs/handbook/variable-declarations.html – crashmstr Aug 12 '16 at 17:45
  • Since JS doesn't have block scope, only function scope, you only create `spotId` once and then all other iterations of the loop use (and modify) the same `spotId`. Refer to Sushanth's answer. – CoconutFred Aug 12 '16 at 17:51
  • it's because of closure, to print respective number you need to do either of the following modification, - you could use `let` instead of `var` - or you can use self executing anonymous function – Brajendra Swain Aug 12 '16 at 17:57

2 Answers2

1

It the case of classic closure problem.

To solve we generally pass the arg to the scope, which forms a closure at the time of excecution.

(function(scopedSpotId) {
    return function() {
       console.log('CLICKED: ' + scopedSpotId); 
    }
}(spotId))

You will have to return a new function for each element in the loop.

((scopedSpotId) ->
  ->
    console.log 'CLICKED: ' + scopedSpotId
    return
) spotId
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • If you want, you can add this working code as an example: L.marker([spot.latitude, spot.longitude], {icon: this.mapService.getSchoolIcon() }) .addTo(this.map) .on('click', (function(scopedSpotId) { return function() { console.log('CLICKED: ' + scopedSpotId); } }(spotId)) ); – rakete Aug 12 '16 at 17:56
1

Replacing var spotId with let spotId should fix the issue as it will make spotId a block scope variable.

Nick Uraltsev
  • 24,607
  • 4
  • 25
  • 14