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 ...
Get Testable JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.