Reputation: 153
Is there a way to "listen" to dynamic text? I have this dynamic textfield on the stage and I want to call a function once the the dynamic text has been changed. I tried to add event listener but it seems to work only on INPUT text. Any suggestions? Thanks
Upvotes: 0
Views: 2449
Reputation: 22604
While @annonymously's answer works, attaching enterFrame listeners to wait for text change (or any change, for that matter) is not a good idea - the text might not change at all, then why would you run a piece of code many times per second, if it's avoidable? Not to mention the fact, that you'd have to do it over and over again for each new text field instance you want to monitor.
It is better to react to actual changes, and these are caused by your own setting of properties. You should simply extend the TextField class and override the setters for htmlText and/or text to dispatch a change event:
override public function set text ( text : String ) : void {
super.text = text;
dispatchEvent (new Event (Event.CHANGE);
}
Upvotes: 4
Reputation: 3899
You can write very simple subclass which allows you to listen text change events.
Sublass:
package
{
import flash.events.Event;
import flash.text.TextField;
public class CustomTextField extends TextField
{
public function CustomTextField()
{
super();
}
override public function set text( value:String ):void
{
if( super.text != value )
{
super.text = value;
dispatchEvent(new Event(Event.CHANGE, true));
}
}
}
}
Usage example:
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
public class CustomTextFieldTest extends Sprite
{
private var tf:CustomTextField;
public function CustomTextFieldTest()
{
tf = new CustomTextField();
tf.x = tf.y = 10;
tf.width = tf.height = 200;
tf.addEventListener(Event.CHANGE, onTfChange);
addChild(tf);
stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
}
private function onTfChange( e:Event ):void {
trace("text changed, new text: '" + tf.text + "'");
}
private function onMouseDown( e:MouseEvent ):void {
tf.text = "some random text: " + Math.round(100 * Math.random());
}
}
}
Upvotes: 1
Reputation: 4708
Only input text dispatches CHANGE events, as you said. You'll have to work around it, perhaps like this:
var oldText:String = "";
function changeEnterFrame (e:Event) {
if (oldText != textField.text) {
// Do your stuff here
}
oldText = textField.text;
}
addEventListener(Event.ENTER_FRAME, changeEnterFrame);
Upvotes: 0
Reputation: 90766
Did you try the CHANGE
event? It should work for all types of TextFields including non-input ones.
Upvotes: 0