Saturday 8 August 2009

EventListener

This is a little class I wrote that make it a bit easier creating and removing event listeners.

If you have ever written code like this:

public function set model( value : myPM ) : void
{
if( _model )
{
_model.removeEventListener(
"someEventType",
myFunction );
}

_model = value;

if( _model )
{
_model.addEventListener(
"someEventType",
myFunction );
}
}

Then EventListener should make your life a bit easier. The above code in MXML would become:

[Bindable]
public var model : MyPM;

]]>

target="{ model }"
type="someEventType"
handler="{ myFunction }"
/>

And in an as file:

private var domainListener : EventListener = new EventListener(
null,
DemoDomain.SAMPLE_DOMAIN_EVENT,
domainHasDoneSomething );

public function set demoDomain( value : DemoDomain ) : void
{
domainListener.target = value;

_demoDomain = value;
}

I think it makes your code look a bit nicer – especially in mxml files where you can just declare the event listener and use bindings.

There is also a passEvent property that determines if the event is passed to the handler function.

I’ve put a demo of it in use here with view source enabled and a download of the source code. This demonstrates an event listener with a target of a domain model. You can then inject the domain model into the PM, the PM then dispatches an event when it receives an event form the domain. IF you remove the domain from the PM the event listener is the cleaned up and the PM no longer dispatches events.

Let me know if you find it useful.

No comments:

Post a Comment