Search code examples
actionscript-3observer-pattern

What is the purpose of hasEventListener and willTrigger in IEventDispatcher?


I'm implementing the observer pattern for a project in a similar way as AS3 does it, i.e. with the IEventDispatcher interface. The reason is because I'm quite fond of it. I know it has received some critisism, but I like it.

However I'm a bit of a perfectionist so I would like to slim it down if possible. The IEventDispatcher interface has the methods hasEventListener and willTrigger and I don't really understand what those methods are good for. I understand, as the documentation say, that they are for checking if there are any listeners registered for a particular event. But... when would one actualy want to check that? Does anyone have a use case where those methods are indispensable?


Solution

  • I believe internally there were some calls to dispatchEvent that would first check if any listeners were present before dispatching the event. I recall this being an issue where if certain listeners weren't registered other code didn't execute, though I can't recall the exact case right now.

    One good way to figure this out would be to grep the Flex source and see how they are used there.

    Edit Just did a grep for hasEventListener on Flex source 4.9.1 and it comes up in 151 files. Lots of places it appears to just check if any event listeners are registered for some event type before it dispatches the event (to avoid unnecessary event creation and dispatch calls I would guess). In searching for willTrigger I find it used for similar situations.