Often I want to respond to events in a component, but I don't want it to need to know anything about the component that is taking action on it. This is often when I am using a generic component on my site.
The Observer pattern is perfect for this.
I didn't find an existing Observer implementation in ColdFusion that I loved and I wanted to try my hand at it, so I created Observer.cfc.
So, Let's use my DataLogger component as a real world example. It logs data changes in a generic table. For now, don't get caught up in the utility of that component, just see how it works.
DataLogger needs to respond to actions that take place in my DataMgr service. My DataMgr service, however, doesn't know anything about DataLogger. It does, however, announce events to Observer.
So, Observer is passed in to DataMgr in initialization and it is passed into DataLogger in initialization as well.
When DataLogger is initialized, it calls the following code:
Listener = This,
ListenerName = "DataLogger",
ListenerMethod = "logAction",
EventNames = "DataMgr:afterInsert,DataMgr:afterDelete,DataMgr:afterUpdate"
That makes sure that any time that Observer hears any of the events listed in "EventNames" that it calls the "logAction".
Here is the code in DataMgr:
The Arguments for all of those methods will include "tablename", "action", and "data".
When the "announceEvent" method of Observer is called, it will call every listener for that event with the passed in arguments. In this case, calling the "logAction" method of DataLogger.
Observer has a few other minor features, but at its heart, it is that easy.
If you need any help with com.sebtools, or ColdFusion in general, let me know.