2 title: Flux architecture
8 * __Dispatchers__ receive *actions* that get dispatched to its listeners.
10 * __Stores__ are objects that store data, usually changed from a dispatcher listener.
12 * __Views__ are React components that listen to Store changes, or emit *actions* to the dispatcher.
19 [A dispatcher][dispatcher] emits events (`.dispatch()`) to its listeners (`.register(fn)`).
22 var Dispatcher = require('flux').Dispatcher;
27 d.dispatch({ action: 'edit', ... };
30 token = d.register(function (payload) {
31 payload.action === 'edit'
35 ### Ensuring proper order
37 With multiple listeners, you can ensure one is fired after another using `.waitFor()`.
40 token1 = d.register(...);
42 token2 = d.register(function (payload) {
44 // ensure receiver 1 is fired before this
45 d.waitFor([ token1 ]);
53 [Object.assign](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) is the preferred way to subclass Dispatcher (think `$.extend`).<br>
54 You can also make *action creators*, which are shortcuts for `dispatch()`.
57 var Dispatcher = require('flux').Dispatcher;
58 var assign = require('object-assign');
60 var AppDispatcher = assign({}, Dispatcher.prototype, {
63 handleViewAction(action) {
65 source: 'VIEW_ACTION',
78 Stores are just like objects.
81 var TodoStore = { list: [] };
85 Sometimes they're eventemitters, too. Usually it's used to emit `change` events for views to pick up.
88 var TodoStore = assign({}, EventEmitter.prototype, {
92 TodoStore.emit('change');
93 TodoStore.on('change', function () { ... });
97 Logic can sometimes belong in stores.
102 return this.list.every(item => item.active);
110 ## Stores and dispatchers
113 Make a Dispatcher and Stores.
116 d = new Dispatcher();
117 TabStore = { tab: 'home' };
121 Dispatch events to alter the store.
124 d.dispatch({ action: 'tab.change', tab: 'timeline' });
126 d.register(function (data) {
127 if (data.action === 'tab.change') {
128 TabStore.tab = data.tab;
137 ### Listen to dispatchers
138 Views (React Components) can listen to Dispatchers.
141 var TodoApp = React.createClass({
143 componentDidMount() {
144 this.token = AppDispatcher.register((payload) => {
145 switch (payload.action) {
153 componentDidUnmount() {
154 AppDispatcher.unregister(this.token);
161 Or to Stores's `change` events.
165 componentDidMount() {
166 TodoStore.on('change', this.onChange);
169 componentDidUnmount() {
170 TodoState.removeListener('change', this.onChange);
183 * [Dispatcher API][dispatcher]
184 * [React cheatsheet](react.html)
185 * [Dispatcher.js source](https://github.com/facebook/flux/blob/master/src/Dispatcher.js)
186 * [Flux-todomvc explanation](https://github.com/facebook/flux/tree/master/examples/flux-todomvc)
188 [dispatcher]: http://facebook.github.io/flux/docs/dispatcher.html