Archive for November, 2008

11
Nov

Passing Arguments with Events


One of the questions about ActionScript 3 that I am most often asked is how to send arguments to a listener function along with an event. Recently, a reader named Jim asked just such a question.

To provide some background for this question, you could send argument data to a standard function like this?

function showMsg(msg:String):void {
    trace(msg);
}
showMsg("Claire");

However, in an event listener, only one argument is allowed in the listener function: the argument responsible for receiving the event data. Using a standard mouse click listener as an example…

stage.addEventListener(MouseEvent.CLICK, showMsg, false, 0, true);
function showMsg(evt:MouseEvent):void {
    trace("hello");
}

…the kind of question asked is, can you do something like this:

stage.addEventListener(MouseEvent.CLICK, showMsg, "hello",
                       false, 0, true);
function showMsg(evt:MouseEvent, msg:String):void {
    trace(msg);
}

The answer is, not out of the box. The existing AS3 events do not provide for this capability. However, to answer Jim’s question, the best way to pass arguments with an event is to create your own event class by extending AS3’s Event class.

Continue reading ‘Passing Arguments with Events’




Speaking



Archives