2
votes

There are multiple MovieClips that will be dynamically placed on stage. These MovieClips are coded to be buttons. I'm trying to figure out--when a user clicks on the MovieClip...figure out which object on the flash stage the user clicked on.

Inside function toggleClick I put the trace statement:

trace("movieClip Instance Name = " + e.target.name);

In the OUTPUT window:

movieClip Instance Name = instance5 
movieClip Instance Name = instance12 
movieClip Instance Name = instance5 
movieClip Instance Name = instance32 
movieClip Instance Name = instance5 
movieClip Instance Name = instance59 

That doesn't seem the way to get a name for the MovieClip that was clicked.

Is getChildByName() the way to do it? If so, any ideas how to use getChildByName() to get the name of the MovieClip that was clicked?

2

2 Answers

7
votes

Before adding a button to the stage you can actually name it

  var myButton:MovieClip = new MovieClip();
  myButton.name = 'button1';

or

  var myButton:MovieClip = new MyButton(); //if you assigned a class name to your MovieClip
  myButton.name = 'button1';

With your example you could do something like this:

  var comp:Comp = new Comp();
  var monitor:Monitor = new Monitor();

  addItemButton( comp, "comp" , {x:100, y:200});
  addItemButton( monitor, "monitor" , {x:30 , y:50} );


  private function addItemButton(item:MovieClip , itemName:String , params:Object):void
  {
     item.addEventListener(MouseEvent.CLICK , clickHandler );
     item.name = itemName;

     // of course params is not necessary, just making a point of  
     // how to centralize your concerns
     item.x = params.x;
     items.y = params.y;

     addChild( item);
  } 

  private function clickHandler(event:MouseEvent):void
  {
     trace( "button clicked:" + event.currentTarget.name );
  }
2
votes

In AS3 when you create a MovieClip dynamically flash asigns it a read-only instance name like you have seen (instance12 for example). The best way to find which movieclip was clicked on is to simply use the currentTarget/target of the MouseEvent (see the difference between the two here: http://www.wastedpotential.com/?p=10).

You would use it like so:

var foo:MovieClip = new MovieClip();
foo.graphics.drawRect(0, 0, 100, 50);
stage.addChild(foo);
foo.addEventListener(MouseEvent.CLICK, clickHandler);

var bar:MovieClip = new MovieClip();
bar.graphics.drawRect(0, 0, 100, 50); bar.y = 100;
stage.addChild(bar);
bar.addEventListener(MouseEvent.CLICK, clickHandler);

//this function will set the x to 100 and the width to 50 of the clicked MovieClip
function clickHandler(e:MouseEvent):void
{
    e.currentTarget.x = 100;
    e.currentTarget.width = 50;
}