In the previous chapter, we looked at how async events work in JavaScript. But in practice, how should we handle those events?
That may sound like a silly question. Just attach a handler to each event your app cares about, right? But when a single event has several consequences, the “one event, one handler” approach forces handlers to grow to gargantuan proportions.
Let’s say you’re building a web-based word processor like Google Docs. Every time a user presses a key, a number of things need to happen: the new character has to be displayed on the screen, the caret has to be moved, the action has to be pushed to the local undo history and synced to the server, spell-check may have to run, and the word count and page count may need to be updated. Carrying out all of these tasks and more from a single keypress handler is a daunting proposition.
From a purely mechanical perspective, every task that we want performed in response to the event does indeed have to be initiated from its handler. But for the sake of us humans, it’s usually better to replace that massive event handler with a more malleable, dynamic construct—one that we can add tasks to, and remove tasks from, at runtime. In short, we want to use distributed events, where a single incident can trigger reactions throughout our application.
In this chapter, you’ll learn to distribute events using the publish/subscribe pattern (aka PubSub). Along the way, we’ll meet several of PubSub’s manifestations: Node’s EventEmitter, Backbone’s evented models, and jQuery’s custom events. With the help of these tools, we’ll be able to un-nest callbacks, reduce duplication, and write event-driven code that’s easy to understand.
3.142.173.89