Responding to application-level events
Although you can have the code that responds to events in the same handler, it's often better to have this code localized to the files (simply for readability and understandability). This means that the event handlers we've discussed so far simply become dispatchers on receipt of an event; they might notify any number of methods in the app when the event occurs.
A lot of JavaScript and UI frameworks have built-in methods to support this event notification system, but here we'll be generic. Such a system needs three methods: a method to register a listener for an event, a method to remove the listener, and a method to dispatch the event to all the listeners. We can define these methods in www/js/app/main.js
.
First, let's define an object to hold our events and listeners, and then define addGlobalEventListener
:
var globalEventListeners = {}; APP.addGlobalEventListener = function addGlobalEventListener( event, listener ) { var EVENT = event.toUpperCase...