0

I'm trying to set up distinct listeners for a list of objects:

for(i=0;i<numInputs;i++) {
    var inPort = inputPorts.get(i);
    var portName = inPort.getProperty("name");
    inPort.shape.attr({ cursor: 'pointer' }).mouseover(function(e) { mouseOverInfo.text("PORT:: "+portName); }); 
}

What's happening right now is that every port object is only getting the very last element's name as its own. So when I mouse over, I get returned only the last object's name.

How to do this properly?

Thanks

JDS
  • 16,388
  • 47
  • 161
  • 224
  • 3
    possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Felix Kling Sep 09 '12 at 16:35

1 Answers1

1

Use self-invoking function like this to avoid closure problem in loop:

for(i=0;i<numInputs;i++) {
  (function(i){
    var inPort = inputPorts.get(i);
    var portName = inPort.getProperty("name");
    inPort.shape.attr({ cursor: 'pointer' }).mouseover(function(e) { mouseOverInfo.text("PORT:: "+portName); }); 
  })(i)
}
Blaster
  • 9,414
  • 1
  • 29
  • 25