0

I have this jsfiddle and I am trying to call different functions using object keys.

i.e.

  var LaneWizard = {
    targets: {
      Lane: $('.lane-colors span'),
      AltLane: $('.alt-lane-colors span')
    },
    prepTargets: function() {
      for(var t in LaneWizard.targets) {
        LaneWizard.targets[t].on('click', function() {
          LaneWizard['change'+t+'Color']($(this));
        });
      }
    }
  }

In the example, there are two (2) concentric circles. The outer circle should be controlled by the first row (Lane Color) and the inner circle by the second row (Alternate Lane Colors).

I can't figure out why they are all changing the color of the inner circle.

Scimonster
  • 32,893
  • 9
  • 77
  • 89
esswilly
  • 229
  • 3
  • 10
  • 3
    possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Scimonster Aug 10 '14 at 18:21
  • My fault...wasn't sure how to word it. Thank you. – esswilly Aug 10 '14 at 18:39

1 Answers1

1

Value 't' has last value always. Make something like this:

prepTargets: function() {
  for(var t in LaneWizard.targets) {
    LaneWizard.attachClick(t);
  }
},
attachClick: function(t) {
  LaneWizard.targets[t].on('click', function() {
    LaneWizard['change'+t+'Color']($(this));
  });
}
Lyubimov Roman
  • 1,269
  • 15
  • 27