views:

25

answers:

3

I often have an function / action that is performed on a mouse event (say, MouseEvent.CLICK) that has to be moved to:

  • happen inside of an animation (at a given frame label)
  • happen at an event (say, Event.COMPLETE)
  • happen when another item is added to the stage or removed from the stage

What is the best OOP way to encapsulate such activities so that I am not constantly rewriting my code?

By the way, I should also mention that this function also being moved from one display object to another, not the just event that it is listening for...

A: 

Pardon me , but I do not understand what you are referring to by saying you have to move a function from one display object to another.

From the bits I understand, you wish to use a mouse click event/function during other events too (like the ones you specified), irrespective of the place it is to be called.

If that is the case & the function is to be used very often as you say, I'd say make it a static function.

loxxy
I should clarify...say I have an action that is fired off when the user clicks on Display Object A. But then...say the client decides that the same action should be moved over to when an animation on Display Object B finishes...what is the best way to encapsulate these actions for changes such as this?
redconservatory
+1  A: 

You can setup your event handler to take a single parameter like this:

protected function actionHandler(e:Event = null):void {
    //handler code here.
}

You can then reference it via a MouseEvent, anything that extends Event, or call it without providing a parameter in cases where it is not event driven. Testing for the type of e (or if e is null) within the handler can give you more precise control over what to do in specific circumstances.

As long as the handler isn't really being used to do two completely different things on those different events/circumstances, this should be fine; however, if you are really branching the actions within the handler, you should use more than one event handler to create more maintainable code.

Tegeril
A: 

If several objects share common functions , you can create an Abstract class your objects could subclass.

public class MyDisplayObjectAbstract extends MovieClip
{
     protected function mouseEventListener(event:Event):void
     {
          gotoAndStop('frameLabel')
     }

     protected function completeEventListener(event:Event):void
     {
        //do whatever
     }
}

Then you can link your objects to a class like the following and if necessary override some of the functions

public class ObjectOne extends MyDisplayObjectAbstract
{
   override protected function mouseEventListener(event:Event):void
   {
       //do whatever
   }
}
PatrickS