Cover by Mark Ethan Trostler

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Chapter 3. Event-Based Architectures

Using factories of various abstractions, façades, and other patterns is not the only way to decouple dependencies and isolate code. A more JavaScript-oriented approach involves the use of events. The functional nature of JavaScript makes it an ideal language for event-based programming.

The Benefits of Event-Based Programming

At their core, all applications revolve around message passing. Tight coupling can occur because the code needs to have a reference to another object so that it can send the object a message and perhaps receive a reply. These objects are global, passed in, or injected via a function parameter, or they are instantiated locally. Our use of factories in the preceding chapter enabled us to pry away the local instantiation requirement; however, we still need the object to be available locally in order to pass messages to it, which means we still must deal with global or injected dependencies. Global dependencies are dangerous: any part of the system can touch them, making bugs very difficult to track down; we can accidentally change them if we have a variable by the same or a similar name declared locally; and they cause data encapsulation to break since they are available everywhere, making debugging very difficult. JavaScript makes declaration and use of global variables very easy, and the environment typically provides several global variables (e.g., the window object in the global scope), as well as global functions and objects ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required