Dispatcher is used to broadcast payloads to registered callbacks. This is different from generic pub-sub systems in two ways:
Check out Dispatcher.js for the source code.
register(function callback): string
Registers a callback to be invoked with every dispatched payload. Returns a token that can be used with waitFor()
.
unregister(string id): void Removes a callback based on its token.
waitFor(array<string> ids): void Waits 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): void Dispatches a payload to all registered callbacks.
isDispatching(): boolean Is 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 CityStore
:
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
that CountryStore
is updated before the callback that updates CityStore
needs to query its data.
The usage of waitFor()
can be chained, for example:
The country-update
payload will be guaranteed to invoke the stores'
registered callbacks in order: CountryStore
, CityStore
, then
FlightPriceStore
.