Chris Tonkinson
Chris Tonkinson

Reputation: 14469

AS3 - question about symbol binding

I'm new to AS3, and can't figure out why this loop isn't behaving the way it "should."

for each (var s in [_set, _set.otherSet]) {
  for each (var f in [s.frame_top_mc, s.frame_bottom_mc]) {
    f.addEventListener(MouseEvent.CLICK, function( ):void {
      _score[f.category] += 1;
      madeSelection(f);
    });
  }
}

How can I give each anonymous function a reference to each object represented by f, rather than a simple reference to f each time?

Specifically, why is it that each copy of the anonymous function gets bound to a single reference to f? How (I should say why) exactly does AS3 differ from JavaScript in this regard?

Upvotes: 2

Views: 125

Answers (1)

Adam Smith
Adam Smith

Reputation: 1937

It needs to be like this:

for each (var s in [_set, _set.otherSet]) {
  for each (var f in [s.frame_top_mc, s.frame_bottom_mc]) {
    f.addEventListener(MouseEvent.CLICK, function( e:MouseEvent ):void {
      _score[e.currentTarget.category] += 1;
      madeSelection(e.currentTarget);
    });
  }
}

The problem is that your closure is closing over the loop variable f itself rather than each thing f is being used to reference within the loop. After the loop completes, f is left as reference to the last thing in the list you looped over. f is not being de-referenced when the closure is created, but when it's executed.

Upvotes: 2

Related Questions