user1503000
user1503000

Reputation: 45

actionscript 3 function cannot access manual movieclip

I'm new to actionscript 3.0. I had the following code:

num0.addEventListener(MouseEvent.CLICK, num0_click);
function num0_click(event:MouseEvent):void
{
    trace(num0);
}

With num0 is a manually added movieclip on the stage and not a member of any other movieclip. I had the output is null. Would you please explain the situation and teach me how to access num0 inside a function like that.

EDIT

The weird thing is that the function works fine if not used as a event listener:

trace(num0);

num0.addEventListener(MouseEvent.CLICK, num0_click);
function num0_click(event:MouseEvent):void
{
    trace(num0);
}

num0_click(null);

the output as following

[object ...]
[object ...]

and when the movie clip instance num0 is clicked (on the swf):

null

Upvotes: 0

Views: 126

Answers (1)

pho
pho

Reputation: 25490

Quite simply,

event.currentTarget gives you the object that is currently processing / handling that event.

Since your event handler num0_click is attached to num0, event.currentTarget will return what you require.

EDIT

A reference to num0 is not stored anywhere (from the code you have given). If you want to access num0 by that name again later, you must declare a variable like so, in the Class scope (or if you aren't using classes, then outside all functions).

var num0:MovieClip;

then, you can instantiate it and refer to it in any function like this:

function init():void {
    num0=new MovieClip();
}

function stop():void {
    num0.stop();
}

EDIT 2 You can also declare the listener function in-line in the addEventListener.

num0.addEventListener(MouseEvent.CLICK, function (event:MouseEvent):void {
    trace(num0);
});

Upvotes: 0

Related Questions