Friday 13 July 2012

CFML: The difference between events and event handlers

G'day:
Here's another quick about Application.cfc.

In a conversation a few weeks back I was talking with a colleague about the applicationStop() function that was added to ColdFusion in CF9. Docs here.

I can't recall the exact gist of the conversation, but we got to the point where my colleague suggested that rather than stopping the application, it could simply be restarted by calling onApplicationStart() (or a combination of onApplicationEnd() and onApplicationStart() or something). This is the same conversation that resulted in my earlier post about the single-threadedness of onApplicationStart().

One thing to bear in mind here is that calling onApplicationStart() does not start your application. It's just something that gets called when ColdFusion starts the application. Obviously a lot of what constitutes your application being in a "started" state is the code that gets executed when onApplicationStart() runs, but onApplicationStart() is not in and of itself what causes an application to start.


Similarly, onApplicationEnd() doesn't end your application. ColdFusion handles the application ending... it just has the courtesy of allowing use to specify some of our own code that runs when it takes the application down. Same with sessions: running onSessionStart() doesn't start a session, and running onSessionEnd() doesn't stop the session. And, yeah, samesame with onRequestStart() and onRequestEnd(): they don't start and stop a request (those two are a bit more obvious).

This might seem obvious to people, but it does trip a lot of people up, and I include myself in that group until I sat back and reflected one day.

The thing is that there's two different notions here; an event, and an event handler. In the process of going about its business, ColdFusion will cause events to happen, such as starting an application, session or request, and at some later point in time it ends them too. But those are the events, and it's ColdFusion that performs them. What Application.cfc gives us is the ability to specify event handlers which ColdFusion calls as part of it performing the actual event. So ColdFusion performs/executes/whatever-you-want-to-call-it an event (I dunno what the best technical term is? Anyone?), and then it calls our event handler from Application.cfc. What this doesn't mean is that the opposite is true: running the event handler doesn't cause the event to occur.

A way to easily see the distinction here is to forget about ColdFusion and think about JavaScript for a moment. If one clicks a mouse button, a click event occurs, and in turn an onClick event handler could run. However the reverse is obviously not true: running the onClick handler obviously doesn't cause the mouse button to depress. That's probably a good way of thinking about it. It's certainly helped me keep it straight in my head.

And now it's time for the pub.

--
Adam