Calling functions from a textfield in as3



The good old asfunction in as2 is no more. so does that mean we cant call action script functions from text fields ? Well yes we can . asfunction mechanism has been replaces by a more prominent and organized methodology in action script 3.0. flash.text.TextField dispatches event:link . Means we can setup the text to broadcast event when it is clicked. We can also pass in parameters with this event.

Following example shows how to control a movieclip’s navigation with text links.

Get Adobe Flash player

This code resides in the first frame of the movie.


textBox.htmlText = "<a href="\">Sit</a>";
textBox.htmlText += "<a href="\">Stand</a>";
textBox.addEventListener(TextEvent.LINK, clickHandler);

function clickHandler(linkEvent:flash.events.TextEvent)
{
switch(linkEvent.text)
{
case "frame1":
frog.gotoAndStop(1);
break;

case "frame2":
frog.gotoAndStop(2);
break
}
}

As you see the code is pretty short. For design arrangements , we will create a movie clip, with a different picture in each of its frame, and a total of two frames. The movie clip will have “stop()” in its first frame to prevent auto play.

Next we set up a text field on stage with its HTML rendering turned on. having done this we give it a instance name : textBox and get back to our code for explanation.

textBox.htmlText = "<a href="\">Sit</a>";
textBox.htmlText += "<a href="\">Stand</a>";
textBox.addEventListener(TextEvent.LINK, clickHandler);

We assign html text to the text field’s htmlText property. note the event:frame2
event is the type of event we broadcast (an object of event type). This event is actually of type TextEvent.
But it dosent matter here when broadcasting. Just passing a generic event object is ok. The frame1 and frame2 are the text property of the TextEvent.

Now we assign a event listener for the text field which handles the “TextEvent.LINK” . now again the text field need not be the object to assign the listener to . It can be assigned even to the stage, because the “TextEvent.LINK” will be broadcasted only when user click on the text.

Finally we create our handler -

function clickHandler(linkEvent:flash.events.TextEvent)

which takes an object of type TextEvent. we then test for the text property of the TextEvent using simple switch case to determine which text was clicked. Accordingly we change the frame of the movieclip on the stage. simple enough :)

Download fla source here

Popularity: 14% [?]




October 18, 2009   Posted in: Actionscript 3.0, General

Leave a Reply