DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 8.15 Responding to Scroll Events

8.15.1 Problem

You want to have some actions performed when a text field's contents are scrolled.

8.15.2 Solution

Define the text field's onScroller( ) event handler method. Alternatively, you can use a listener object.

8.15.3 Discussion

When a text field is scrolled vertically or horizontally (meaning that the scroll or hscroll property has been changed either by your custom ActionScript code or by a scrollbar), the onScroller( ) method is automatically invoked. By default, a text field's onScroller( ) method is undefined, but you can assign it a reference to a function:

myTextField.onScroller = function (  ) {
  trace("text is scrolled");
};

You can also create listener objects for a text field that are notified when the text is scrolled. Listener objects can be any kind of object, such as another text field, a movie clip, or a custom object type. You should define an onScroller( ) method for the listener object, then register the object to the text field using the addListener( ) method. Call the addListener( ) method from the text field and pass it a parameter that references the listener object (the object with onScroller( ) defined). For example:

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

You can add multiple listeners to one text field. Working with listeners is a powerful technique because it allows you to define actions that should occur on multiple objects when a text field is changed in some way. This is much more powerful than placing all the actions within a single method assigned to the text field for several reasons. For one thing, it is a good practice to keep actions specific to an object assigned to that object and not to other objects. (For example, a ScrollBar component configures itself as a listener for the targeted text field. If the text field changes programmatically, the ScrollBar component independently updates its own scroller position to match the text field.) Additionally, the listener objects can reference themselves with the this keyword, which keeps your code as abstract as possible. Here, two objects are added as listeners:

myListener = new Object(  );
myListener.onScroller = function (  ) {
  // Actions go here.
};

myMovieClip.onScroller = function (  ) {
  this._x++;
};

myTextField.addListener(myMovieClip);
myTextField.addListener(myListener);

You can remove a listener by invoking the text field's removeListener( ) method, passing it a reference to the listener object to remove:

myTextField.removeListener(myListener);

8.15.4 See Also

For more information on listeners, see Recipe 12.11, along with Recipe 8.26 and Recipe 8.27.

    [ Team LiB ] Previous Section Next Section