Wednesday, September 19, 2007

Populating a TextField before it exists

A friend of mine posted the following Flash problem the other day:

I tell a movie clip to go to a frame. I want to put something in text fields on that frame, or set some property of some movie clip on that frame. But if I gotoAndStop, and then on the next line of AS try to set something, I get an error. I need to wait for the frame to start, or the objects on the frame don't exist yet. So I have to put a function call on the frame to call a second function to do the setting later on.

The is quite messy. Surely there has to be a better way.

I came up with the following solution, which I think is fairly elegant. You make a symbol with a TextField in it. Set the symbol to extend from a class which has a public static variable you can set, then when the symbol is instantiated later it uses that class variable in the constructor. This works because the class is loaded when you reference it, it doesn't matter that an instance of the class does not yet exist.

The static variable could be an object so you can better identify what value should be populated. You can get the instance name in the constructor to determine which property of the object in the class variable to use. Here's an example of the class:
package {
import flash.display.MovieClip;
import flash.text.TextField;
public class JRNTextField extends MovieClip{
// should use a getter/setter
public static var mytext:Object = new Object();
public function JRNTextField(){
textInSym.text = JRNTextField.mytext[this.name];
}
}
}

In frame 1:
JRNTextField.mytext.asdf = "hello";
JRNTextField.mytext.qwer = "goodbye";
In frame 2:
stop();

Frame 2 has two instances in the timeline of a symbol that extends the JRNTextField class.

The symbol contains a dynamic TextField that is named "textInSym".

The instances on frame 2 are named "asdf" and "qwer". As hoped, they get
populated with "hello" and "goodbye", respectively.