开发者

When to extends EventDispatcher

开发者 https://www.devze.com 2023-01-10 22:06 出处:网络
Simple question..I was wondering when you guys extends EventDispatcher in your class. It seems to me that as long as we have import event package, we can dispatchEvent without problems....I saw someti

Simple question..I was wondering when you guys extends EventDispatcher in your class. It seems to me that as long as we have import event package, we can dispatchEvent without problems....I saw sometime people extends EventDispatcher in their class...not sure why...anyone care to explain? Thanks a milli开发者_如何学Goon...


I think you might be confusing the fact that many objects in AS3 extend EventDispatcher higher in the inheritance tree with only needing to import the flash.events package in order to dispatch events. For instance many DisplayObject classes extend the EventDispatcher. Here are a couple of examples:

Shape » DisplayObject » EventDispatcher » Object

Sprite » DisplayObjectContainer » InteractiveObject » DisplayObject » EventDispatcher » Object

Typically I will extend EventDispatcher any time I am working with a custom class that just needs to communicate to objects outside of it's scope that some internal property has changed or that some function is occuring. Here is an example:

public class Clock extends EventDispatcher
{
     protected var _tick:uint;

     protected function run():void
     {
         if( _tick + 1 > 60 ) {
             _tick = 0;
         } else {
             _tick++;
         }
         dispatchEvent( new Event( Event.CHANGE ) );
     }

     public function getTick():uint { return _tick; }
}

Sometimes it is "important" to keep the internal details of an object read only. In the case of the above example, when the run() method is called, the Clock class performs some internal logic and then dispatches an event indicating that something has changed. Any class that is listening for that event can then call the public getTick() method to find out the value of _tick. This hides the implementation and protects the _tick variable from being changed by outside classes and at the same time provides an interface through which the Clock can be read.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号