user3670426
user3670426

Reputation:

AS3 : How to identify which button was pressed?

I have a MovieClip with a button inside it named t_bt. I have exported that MovieClip to action script and gave it a class name of e_panel . I created 50 instances of e_panel to stage with this code:

var e_p_y:Number=0;

for ( var i:Number=1;i<=50;i++)
{
    var e_p:MovieClip = new e_panel();
    e_p.x = 50;
    e_p.y = e_p_y;
    e_p.t_bt.addEventListener(MouseEvent.MOUSE_UP, f1);
    addChild(e_p);
    e_p_y = e_p_y+105;
} 

now I want identify which button was pressed by user in function f1.

function f1(event:MouseEvent):void
{
    //...what should I write here?
}

Upvotes: 1

Views: 407

Answers (3)

edrian
edrian

Reputation: 4531

e_panel clip must have an associated E_Panel class that extends MovieClip and (for example) adds an index property to hold the index of the item.

Then, on f1 you could do:

function f1(event:MouseEvent):void
{
    var e_panel:E_Panel = event.currentTarget.parent as E_Panel;
    trace(e_panel.index);
}

Remember to set index property upon movie clip creation

Hope it helps

Extra info

Create this a class for E_Panel and link it to movieClip with library properties

public class E_Panel extends MovieClip 
{

    private var _index:int;

    public function E_Panel(index:int) 
    {
        super();
        _index = index;
    }

    public function get index():int {
        return _index;
    }
}

Then in your code:

var e_p:E_Panel = new e_panel(i); //"i" is the iteration counter
e_p.x = 50;
... //Etc

Upvotes: 0

BadFeelingAboutThis
BadFeelingAboutThis

Reputation: 14406

Every event has a property called currentTarget, which will be a reference to the object you added the event listener to.

So in your case:

function f1(event:MouseEvent):void
{
     var t_bt:DisplayObject = event.currentTarget as DisplayObject; //would be the t_bt instance that was clicked (typed as a basic object)
     var e_p:MovieClip = DisplayObject(event.currentTarget).parent as MovieClip //would be the e_p of the item clicked

     //so if you wanted to do something like make the whole panel half transparent once clicked
     e_p.alpha = .5;

     //if you wanted to get the index of the button clicked
     trace("Button Clicked: ", e_p.parent.getChildIndex(e_p));
}

In contrast, the target property of an event is the actual displayObject that was clicked (which could be the same as currentTarget or a child of the currentTarget)

Upvotes: 2

Ravi Allam
Ravi Allam

Reputation: 20

Try this Code::

var e_p_y:Number=0;
for ( var i:Number=1;i<=50;i++)
{
    var e_p:MovieClip= new e_panel();
    e_p.x=50;
    e_p.y=e_p_y;
    e_p.t_bt.addEventListener(MouseEvent.MOUSE_UP, f1);
    addChild(e_p);
    e_p_y=e_p_y+105;

    e_p.name= i+'';

}

Now write this code in f1 function::

function f1(event:MouseEvent):void
{
    trace(event.currentTarget.name);
}

Upvotes: -1

Related Questions