In this chapter, we’ve learned about distributing events via PubSub, one of the most fundamental JavaScript design patterns. When you’re not subscribing to the events that are being published, PubSub is completely unobtrusive. The key to using PubSub properly is deciding which entities to distribute events through.
We’ve seen that any object can be used for PubSub, simply by inheriting from something like Node’s EventEmitter. Whenever an object is associated with a set of async tasks or I/O events, it’s a good idea to make it evented.
One class of evented object is the models in MVC libraries like Backbone.js. These models both contain application state and announce changes to it. Change events can trigger application logic, DOM updates, and synchronization with the server. It all feels very natural, which explains why Backbone has become a smash-hit library.
We’ve also seen that jQuery is great for distributing events related to changes in the DOM, not just the DOM events provided by the browser. Evented objects and DOM events complement each other perfectly, helping to keep the application’s state and view encapsulated from each other.
All of these are examples of PubSub in action. However, as versatile as it is, PubSub isn’t the right tool for every job. In particular, it’s a poor fit for one-shot events, when an async function performs a task whose completion or failure needs to be handled in a unique way. (An Ajax request is a common example.) One tool for solving that problem, called a Promise, is the subject of the next chapter.
52.14.123.103