开发者

listener functions created in an addFrameScript not acting as closures?

开发者 https://www.devze.com 2023-03-11 04:07 出处:网络
For reference, here\'s a question I asked earlier today regarding this same project: Reference objects on stage/frame from document class

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开发者_Go百科.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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消