Dispatcher is used to broadcast payloads to registered callbacks. This is different from generic pub-sub systems in two ways:
- Callbacks are not subscribed to particular events. Every payload is dispatched to every registered callback.
- Callbacks can be deferred in whole or part until other callbacks have been executed.
Check out Dispatcher.js for the source code.
register(function callback): stringRegisters a callback to be invoked with every dispatched payload. Returns a token that can be used with
unregister(string id): voidRemoves a callback based on its token.
waitFor(array<string> ids): voidWaits for the callbacks specified to be invoked before continuing execution of the current callback. This method should only be used by a callback in response to a dispatched payload.
dispatch(object payload): voidDispatches a payload to all registered callbacks.
isDispatching(): booleanIs this Dispatcher currently dispatching.
For example, consider this hypothetical flight destination form, which selects a default city when a country is selected:
When a user changes the selected city, we dispatch the payload:
This payload is digested by
When the user selects a country, we dispatch the payload:
This payload is digested by both stores:
When the callback to update
CountryStore is registered, we save a reference
to the returned token. Using this token with
waitFor(), we can guarantee
CountryStore is updated before the callback that updates
needs to query its data.
The usage of
waitFor() can be chained, for example:
country-update payload will be guaranteed to invoke the stores'
registered callbacks in order: