Eduardo Ponce de Leon
Eduardo Ponce de Leon

Reputation: 9696

How to add an event listener to a symbol instead of an instance as3

We have a button symbol that is repeatedly inserted as an instance in several scenes. this button links between scene to scene and basically execute the same function.

Is there a way to add an eventListener MouseEvent.CLICK to the symbol itself so we do not have to re-write a listener for each instance in each scene?

Upvotes: 1

Views: 1193

Answers (2)

strah
strah

Reputation: 6722

Create a class, ie 'LinkingButton'. Inside this class create a click handler which would do what you want.

Then you will need to 'link' your class to the symbol in your library.

If done correctly you only will need to drag the symbol to the stage and it should work straight away. Or if you prefer to use the code it's simple, too:

var myButton:LinkingButton = new LinkingButton();
addChild(myButton);

Upvotes: 2

weltraumpirat
weltraumpirat

Reputation: 22604

You can neither receive mouse events on a symbol (i.e. a Class), nor dispatch any event from it. So that is out of the question.

You could create a new Sprite symbol, place your custom Button in it, and then add a listener in a frame script inside of that Sprite - but that is really messy.

The cleanest way to do this is to add a listener for Event.ADDED to the stage - which is caught whenever any new instance of DisplayObject is added anywhere in the display list - and make a handler function add the appropriate listener to each instance of your special button:

 function onInstanceAdded( event:Event ) : void {
     if( event.target ) is MySpecialButton
         event.target.addEventListener( MouseEvent.CLICK, onSpecialButtonClick );
 }

 function onSpecialButtonClick( event:MouseEvent ) : void {
     doMagicStuffHere();
 }

 stage.addEventListener( Event.ADDED, onInstanceAdded );

Upvotes: 0

Related Questions