Recipe 8.27 Responding to User Text Entry

8.27.1 Problem

You want to perform a task when the content of a text field is modified by user input.

8.27.2 Solution

Assign a function definition to the text field's onChanged( ) event handler method. Alternatively, you can use a listener object with a defined onChanged( ) method and register it with the text field using addListener( ).

8.27.3 Discussion

You can specify actions to be performed each time the content of a text field is changed by user input, whether that change be deleting or cutting characters, typing in characters, or pasting characters. You can define the text field's onChanged( ) event handler method:

myTextField.onChanged = function (  ) {
  trace("the value has been modified");
};

When a user makes any change to the value of an input text field with an onChanged( ) handler defined, the actions defined in the onChanged( ) handler are executed.

You can also define an onChanged( ) method for a listener object (or listener objects). If multiple objects need to be updated when a change occurs in the input text field's value, you should register those objects as listeners. You should define an onChanged( ) method for the listener object and then register the listener with the text field's addListener( ) method. The addListener( ) method takes a reference to the listener object. For example:

myListener = new Object(  );
myListener.onChanged = function (  ) {
  // Actions go here.
};
myTextField.addListener(myListener);

You can use addListener( ) to register as many listener objects as you need. In this way, each listener object handles only the functionality that is applicable to it.

If you want to unregister a listener object, call the removeListener( ) method of the text field at any time, passing it a reference to the listener object to be removed:

myTextField.removeListener(myListener);

Whether using the event handler method or using a listener object, attempt to keep your onChanged( ) definition as streamlined as possible. Remember that the method is invoked every time the user types a character into the text field, so if you try to do too much at once, you can put unnecessary strain on your Flash movie.

8.27.4 See Also

Recipe 8.15



    Part I: Local Recipes
    Part II: Remote Recipes