Monday, 11 February 2013

Keeping the Javascript Beast Contained, Part 2: Events

Last time, I talked about keeping containment within Javascript for DOM manipulation. Today, I want to talk about a different aspect of containment - Javascript events.

A small Javascript application can get away without much structure to their events. Events can 'float around' the application code and a developer can generally cope with understanding the interactions between separate events reasonably well.

As the application grows, this unstructured style of event handling and passing easily becomes a nightmare that you cannot easily reason through. Components that handle and issue events start to interact in unexpected ways and your events have lost containment. They are no longer helping you keep your application components uncoupled, instead you are likely to be triggering events on specific components in order to avoid unintended side-effects. What was supposed to help you keep an application uncoupled has now turned into a nightmare of coupling and spaghetti code that's hard to follow and reason about.

This shows the basic idea we introduced in Gradient.

We have an Application object which handles the integration of the rest of the application with a semantic message model. This fulfils the same role as semantic events, but is more explicit. The coupling between components is somewhat more verbose, but it ensures that our hierarchy remains as a tree, rather than a web, which we personally feel is easier to reason about in our application. The individual components keep containment on the base events and transform them into appropriate semantic events.

This introduces the general idea for dealing with event containment in front-end Javascript. Use custom, semantic events that have meaning, and do not be afraid to introduce new events rather than attempt to shoe-horn a new interaction into an existing event that almost, but doesn't quite, fit. Your components contain the base events and transform them into semantic events, and these semantic events act as messages flowing through your application to trigger behaviour.

Examples are in Coffeescript, as I feel this provides less obscuring of the basic idea, and avoids arguments over how I chose to do a Javascript class, or how I maintained 'this' across scopes, rather than useful discussions about the central idea.

No comments:

Post a Comment