Recipe 9.26.
Calling ActionScript from Hyperlinks
Problem
You want
to call an ActionScript
method when the user clicks a hyperlink.
Solution
Use the event protocol and listen for
link events.
Discussion
Many applications require calling ActionScript
when the user clicks a hyperlink. With ActionScript 3.0, however,
it is a very simple task. First, you must define the hyperlink to
use the event protocol, as follows:
field.htmlText = "<a href='event:http://www.rightactionscript.com'>Website</a>";
When you use the event protocol, the
default behavior does not occur. When the user clicks on a
hyperlink, it normally opens the URL in a web browser. However,
when you use the event protocol, an event is dispatched,
which means you have to register a listener to listen for that
event. The event type is link, and you can use the
flash.events.TextEvent.LINK constant when registering a
listener:
field.addEventListener(TextEvent.LINK, onClickHyperlink);
The event that is dispatched is a
flash.events.TextEvent
type. The text property of the event object contains
the value of the HRef attribute minus the event
protocol. That means that in the preceding example, the value of
the event object's text property is http://www.rightactionscript.com.
Since the hyperlink does not attempt to open a URL in a browser
window when using the event protocol, you don't have to use
a valid URL for the href value. You can use any string
that would be useful in determining which hyperlink the user
clicked.
|