0

For reference, here's a question I asked earlier today regarding this same project: Reference objects on stage/frame from document class

addFrameScript seems to do what I need it to, except for one thing. In the function I'm passing to be added as a frame script, I want to dynamically create some event listeners for buttons, but variables I want closed over the listener functions aren't behaving as expected -- they all end up having the last assigned value of the variable rather than the value it had when the function was defined, as if different scope rules are in effect than normal:

addFrameScript(node_frame - 1,
    function() {
        stop();
        question_txt.text = node_question;
        answers_xml = node_xml.answer;
        for (var i:Number = 0; i < answers_xml.length(); i++) {
            button = getChildByName('answer' + (i+1) + '_btn');
            if (answers_xml[i].attribute('node')) {
                goes_to = answers_xml[i].attribute('node');
                trace(goes_to); 
                button.addEventListener('click',
                    function() {
                        trace(goes_to);
                    });
            }
        }                   
    });

The trace output at first is:

1A
2A
3A

But then afterward, if I click any of the three buttons, they all trace:

3A

Anyone have any insight to what's going on here and/or how I can work around it? Do frame scripts observe different (dynamic rather than lexical?) scoping or something?

Community
  • 1
  • 1
hoff2
  • 774
  • 3
  • 9
  • 25

1 Answers1

2

No, scoping in added frame scripts behave exactly like scoping everywhere else in AS3. Flash late-binds variables, but you're trying to access them as though they're early-bound inside your listener.

Oddly enough, I just answered this same question earlier today here: How do you bind a variable to a function in as3

For more information, I wrote a blog post about this sort of thing here: http://www.scriptocalypse.com/?p=31

Community
  • 1
  • 1
scriptocalypse
  • 4,942
  • 2
  • 29
  • 41
  • I could swear I've used this pattern successfully many times in the past. Could it be that I'm thinking in AS2? – hoff2 Jun 08 '11 at 20:26
  • I don't quite remember. I tried to purge all the AS2 from my head years ago. ;) It's possible that AS2 used to early-bind, but that's not the case any longer if it did. – scriptocalypse Jun 08 '11 at 20:28