Event-driven programming in the browser

On the front end we use events every day but without jQuery many of these wouldn’t exist. DOM Ready has only recently become a real browser event, before that libraries like jQuery and Prototype created and fired it for us.

DOM Ready was a custom event and the functionality for creating custom events exists for us to use. It’s as easy as $Element.trigger(eventType)

What is this event-driven shazbot?

In event driven programming the flow of the program is determined by the Production, Detection, Consumption of and Reaction to events. An event can be defined as a significant change in state. Commonly, our UI events (click, mouseover, etc) are inputs that may cause an event rather than an event in themselves.

Why should you care?

There are many ways to call functions, including direct method calls, callbacks and handler functions. All have a reliance upon other methods/modules. The triggering and handling of events enables us to have extremely loosely coupled code.

For example, we may have a visualization that is based upon a data set. If that dataset is updated we can trigger a custom event to broadcast that the data has been updated. The visualization module may then watch for this event and know that it should refresh. Because these are loosely modules coupled neither of these elements know directly about the other and an error in one would not affect the other.

Is trigger better than amplify or other pub/sub messaging?

We can also take advantage of the event behavior that JS developers are used to by using these custom events on the DOM. You may choose to trigger or handle events at the document level, but when used on child elements they will bubble and can be stopped like any regular event. Used well I think that’s very powerful.

However using the DOM to support our messaging comes with a performance hit, but the pure JS code will always win here. Event-driven programming is a great option to bare in mind when you’re architecting a solution and a great partner to a modular code-base.

Leave a Reply

Your email address will not be published. Required fields are marked *