Pay for Hesitation: eventlistener的機制

Pages

2008年3月19日 星期三

eventlistener的機制

之前在看 Essential ActionScript 3.0時,
看到removeEventListener()時,讓我有點心驚膽跳,就像第一次知道C++中,沒有把用完的物件delete,會造成memory leak那種不安的感覺。


做了一小段筆記,
removeEventListener() unregistering an event listener.(少見)但是書上寫說,在物件死亡前,應先做反註冊的動作,否則eventDispatch會一直存著該物件的listener,佔記憶體不說,最可怕的是會產生無預期的bug。 p.216


諷刺的是,其實這個問題java也是會發生的,只是之前不知道。
下面引述 Fundation ActionScript 3.0 Animation p.34

Now, I’ve been saying that a listener listens for events, but perhaps a more accurate description is thatthe listener is notified of events. Internally, the object that is generating events keeps a list of everyobject that has added itself as a listener. If an object is capable of generating different types of events,such as mouseDown, mouseUp, and mouseMove, it will keep a list of listeners for each event type it can generate. Whenever one of these events occurs, the object runs through the corresponding list handlets each object in that list know what event has occurred. Yet another way of describing events is to say that the object that becomes a listener is subscribing to a particular event. And the object that generates the event is broadcasting the event to all its subscribers. Additionally, if you no longer want an object to listen to events, you can tell it to stop listening, orunsubscribe, by calling the removeEventListener method:
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
This tells the object to remove the listener from its list of listeners for that particular event, so it will not receive further notifications.

其實上面這段也沒講的很清楚,但可以得知的是,eventlistener是會影響performance的,而且當物件被移除時,在event dispacher那註冊的listener似乎不會自動被移除,所以當物件不再使用時,removeEventListener是個重要的習慣。

詳細的細節我晚上再翻一下Essential 那本。

沒有留言: