Thursday 29 April 2010

Observer pattern? Notifications? listener? event? WTF?

I was using a class to broadcast events to any object without referencing them anywhere.
Making a new project on a new machine, i just thought i could grab the equivalent on the great word wide web.
So i Googled 'Observer pattern AS3', 'event broadcaster', 'notification'...

I found there are lots of misunderstanding between what an observer, a listener, an event are...
Some says that the listeners in flash are direct implementation of observer pattern.
But What i wanted was a centralised way to communicate between object. Instead of object directly referencing each others, they just listen to something without knowing where it comes from. This is highly interesting when you want to trigger events that changes lots of thing in your app without having dependencies!


I remember in pureMVC you could register a class Observer and send a notification. And any object in the framework can listen to it without knowing the object which sent it.
This was great exept i think the implementation is tied to the framework, therefore cannot be used standalone.

So i thought (for the 2 people who might read this blog) that i would share my lightweight implementation which i think is simpler and handier:

How it works:
C wants to know when someone say 'something'
C ask B to tell him when someone say 'something'
A say 'something'
B recieve 'something'
B warns C that someone said 'something'
C is happy

A and C doesn't know each others. They lived happily ever after... in their respective corners.

translation in actionscript:
in the class A:
EventBroadcaster.register(this,EventBroadcastsType.BROADCAST_SOMEONE_SAY_SOMETHING,doSomething);

in the class C:
EventBroadcaster.broadcastEvent(EventBroadcastsType.BROADCAST_SOMEONE_SAY_SOMETHING);

and that's it! Then the class A will call the function doSomething()

you can add parameters as well, if you wish:
ex: A.doSomething(eatYourGreen:Boolean,theAgeOfTheCaptain:int)
and in C:
EventBroadcaster.broadcastEvent(EventBroadcastsType.BROADCAST_SOMEONE_SAY_SOMETHING,true,71);

and A will call doSomething with the parameters.
This is just dead simple class , but dead useful.

Download the class here

No comments: