Skip to content

Commit bc4d935

Browse files
committed
[docs] Update Flux TodoMVC Tutorial
1 parent 72e690e commit bc4d935

File tree

1 file changed

+131
-60
lines changed

1 file changed

+131
-60
lines changed

docs/docs/flux-todo-list.md

Lines changed: 131 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -46,63 +46,103 @@ myapp
4646
+ ...
4747
```
4848

49-
Creating a Dispatcher
50-
---------------------
5149

52-
Now we are ready to create a dispatcher. Here is an naive example of a Dispatcher class, written with JavaScript promises, polyfilled with Jake Archibald's [ES6-Promises](https://github.com/jakearchibald/ES6-Promises) module.
50+
Using the Dispatcher
51+
--------------------
52+
53+
We'll use the dispatcher from the [Flux GitHub repository](https://github.com/facebook/flux), but let's go over how to get it into our project, how it works and how we'll use it.
54+
55+
The dispatcher's source code is written in [ECMAScript6](https://github.com/lukehoban/es6features), the future version of JavaScript. To use the future of JS in today's browser's we need to transpile it back to a version of JS that browsers can use. We perform this build step, transpiling from ES6 into common JavaScript, using npm.
56+
57+
You can get up and running with the dispatcher in a variety of ways, but perhaps the simplest is to use [Michael Jackson](https://twitter.com/mjackson)'s npm module version of the Flux project, called [react-dispatcher](https://www.npmjs.org/package/react-dispatcher):
58+
59+
```
60+
npm install react-dispatcher
61+
```
62+
63+
Afterward, you can require the dispatcher in your project's modules like so:
5364

5465
```javascript
55-
var Promise = require('es6-promise').Promise;
56-
var merge = require('react/lib/merge');
66+
var Dispatcher = require('Flux').Dispatcher;
67+
```
68+
69+
Alternatively, you can clone the Flux repo, run the Gulp-based build script with `npm install`, and then simply copy the dispatcher and invariant modules located inside flux/lib/ to the dispatcher directory for your project. This the what we did in the [example code](https://github.com/facebook/flux/tree/master/examples/flux-todomvc/js/dispatcher).
5770

58-
var _callbacks = [];
59-
var _promises = [];
71+
The two most important methods that the dispatcher exposes publically are register() and dispatch(). We'll use register() within our stores to register each store's callback. We'll use dispatch() within our action creators to trigger the invocation of the callbacks.
6072

61-
var Dispatcher = function() {};
62-
Dispatcher.prototype = merge(Dispatcher.prototype, {
73+
```javascript
74+
class Dispatcher {
75+
constructor() {
76+
this._callbacks = {};
77+
this._isPending = {};
78+
this._isHandled = {};
79+
this._isDispatching = false;
80+
this._pendingPayload = null;
81+
}
6382

6483
/**
65-
* Register a Store's callback so that it may be invoked by an action.
66-
* @param {function} callback The callback to be registered.
67-
* @return {number} The index of the callback within the _callbacks array.
84+
* Registers a callback to be invoked with every dispatched payload.
85+
*
86+
* @param {function} callback
87+
* @return {string}
6888
*/
69-
register: function(callback) {
70-
_callbacks.push(callback);
71-
return _callbacks.length - 1; // index
72-
},
89+
register(callback) {
90+
var id = _prefix + _lastID++;
91+
this._callbacks[id] = callback;
92+
return id;
93+
}
94+
95+
// ...
7396

7497
/**
75-
* dispatch
76-
* @param {object} payload The data from the action.
98+
* Dispatches a payload to all registered callbacks.
99+
*
100+
* @param {object} payload
77101
*/
78-
dispatch: function(payload) {
79-
// First create array of promises for callbacks to reference.
80-
var resolves = [];
81-
var rejects = [];
82-
_promises = _callbacks.map(function(_, i) {
83-
return new Promise(function(resolve, reject) {
84-
resolves[i] = resolve;
85-
rejects[i] = reject;
86-
});
87-
});
88-
// Dispatch to callbacks and resolve/reject promises.
89-
_callbacks.forEach(function(callback, i) {
90-
// Callback can return an obj, to resolve, or a promise, to chain.
91-
// See waitFor() for why this might be useful.
92-
Promise.resolve(callback(payload)).then(function() {
93-
resolves[i](payload);
94-
}, function() {
95-
rejects[i](new Error('Dispatcher callback unsuccessful'));
96-
});
97-
});
98-
_promises = [];
102+
dispatch(payload) {
103+
invariant(
104+
!this._isDispatching,
105+
'Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.'
106+
);
107+
this._startDispatching(payload);
108+
try {
109+
for (var id in this._callbacks) {
110+
if (this._isPending[id]) {
111+
continue;
112+
}
113+
this._invokeCallback(id);
114+
}
115+
} finally {
116+
this._stopDispatching();
117+
}
99118
}
100-
});
101119

102-
module.exports = Dispatcher;
120+
// ...
121+
122+
_invokeCallback(id) {
123+
this._isPending[id] = true;
124+
this._callbacks[id](this._pendingPayload);
125+
this._isHandled[id] = true;
126+
}
127+
128+
_startDispatching(payload) {
129+
for (var id in this._callbacks) {
130+
this._isPending[id] = false;
131+
this._isHandled[id] = false;
132+
}
133+
this._pendingPayload = payload;
134+
this._isDispatching = true;
135+
}
136+
137+
_stopDispatching() {
138+
this._pendingPayload = null;
139+
this._isDispatching = false;
140+
}
141+
142+
}
103143
```
104144

105-
The public API of this basic Dispatcher consists of only two methods: register() and dispatch(). We'll use register() within our stores to register each store's callback. We'll use dispatch() within our actions to trigger the invocation of the callbacks.
145+
We use register() to register a store's callback with the dispatcher, and dispatch() to invoke all of callbacks we previously registered. A data payload (the action) is the sole argument provided to the callback.
106146

107147
Now we are all set to create a dispatcher that is more specific to our app, which we'll call AppDispatcher.
108148

@@ -130,7 +170,9 @@ var AppDispatcher = merge(Dispatcher.prototype, {
130170
module.exports = AppDispatcher;
131171
```
132172

133-
Now we've created an implementation that is a bit more specific to our needs, with a helper function we can use in the actions coming from our views' event handlers. We might expand on this later to provide a separate helper for server updates, but for now this is all we need.
173+
Now we've created an implementation that is a bit more specific to our needs, with a helper function we can use when we create actions. We might expand on this later to provide a separate helper for server updates, but for now this is all we need.
174+
175+
You don't actually need to create an AppDispatcher in every application, but we wanted to show it here as an example.
134176

135177

136178
Creating Stores
@@ -372,7 +414,7 @@ Text input, on the other hand, is just a bit more complicated because we need to
372414

373415
As you'll see below, with every change to the input, React expects us to update the state of the component. So when we are finally ready to save the text inside the input, we will put the value held in the component's state in the action's payload. This is UI state, rather than application state, and keeping that distinction in mind is a good guide for where state should live. All application state should live in the store, while components occasionally hold on to UI state. Ideally, React components preserve as little state as possible.
374416

375-
Because TodoTextInput is being used in multiple places within our application, with different behaviors, we'll need to pass the onSave method in as a prop from the component's parent. This allows onSave to invoke different actions depending on where it is used.
417+
Because TodoTextInput is being used in multiple places within our application, with different behaviors, we'll need to pass the onSave method in as a prop from the component's parent. This allows onSave to invoke different action creator methods depending on where it is used.
376418

377419
```javascript
378420
/** @jsx React.DOM */
@@ -497,10 +539,10 @@ module.exports = Header;
497539
In a different context, such as in editing mode for an existing to-do item, we might pass an onSave callback that invokes `TodoActions.update(text)` instead.
498540

499541

500-
Creating Semantic Actions
501-
-------------------------
542+
Creating Actions with Semantic Methods
543+
--------------------------------------
502544

503-
Here is the basic code for the two actions we used above in our views:
545+
Here is the basic code for the two action creator methods we used above in our views:
504546

505547
```javascript
506548
/**
@@ -571,27 +613,56 @@ React.renderComponent(
571613
);
572614
```
573615

574-
Adding Dependency Management to the Dispatcher
616+
Dependency Management in the Dispatcher
575617
----------------------------------------------
576618

577-
As I said previously, our Dispatcher implementation is a bit naive. It's pretty good, but it will not suffice for most applications. We need a way to be able to manage dependencies between Stores. Let's add that functionality with a waitFor() method within the main body of the Dispatcher class.
619+
As our application grows beyond this simple application to contain multiple stores, we'll need a way to be able to manage dependencies between them. That is, Store A might need to derive data based on Store B's data, so Store A would need Store B to update itself first. This functionality is available with the Dispatcher's waitFor() method.
578620

579-
We'll need another public method, waitFor(). Note that it returns a Promise that can in turn be returned from the Store callback.
621+
We would call waitFor() within the store's registered callback like so:
580622

581623
```javascript
582-
/**
583-
* @param {array} promisesIndexes
584-
* @param {function} callback
585-
*/
586-
waitFor: function(promiseIndexes, callback) {
587-
var selectedPromises = promiseIndexes.map(function(index) {
588-
return _promises[index];
589-
});
590-
return Promise.all(selectedPromises).then(callback);
624+
Dispatcher.waitFor([StoreB.dispatcherIndex, StoreC.dispatcherIndex]);
625+
// now do things, knowing that both StoreB and StoreC have updated
626+
```
627+
628+
In the source code, you can see that we are interupting the synchronous iteration over the callbacks and starting a new iteration of callbacks based on the array of dispatcherIndexes passed into waitFor().
629+
630+
```javascript
631+
/**
632+
* Waits for the callbacks specified to be invoked before continuing execution
633+
* of the current callback. This method should only be used by a callback in
634+
* response to a dispatched payload.
635+
*
636+
* @param {array<string>} ids
637+
*/
638+
waitFor(ids) {
639+
invariant(
640+
this._isDispatching,
641+
'Dispatcher.waitFor(...): Must be invoked while dispatching.'
642+
);
643+
for (var ii = 0; ii < ids.length; ii++) {
644+
var id = ids[ii];
645+
if (this._isPending[id]) {
646+
invariant(
647+
this._isHandled[id],
648+
'Dispatcher.waitFor(...): Circular dependency detected while ' +
649+
'waiting for `%s`.',
650+
id
651+
);
652+
continue;
653+
}
654+
invariant(
655+
this._callbacks[id],
656+
'Dispatcher.waitFor(...): `%s` does not map to a registered callback.',
657+
id
658+
);
659+
this._invokeCallback(id);
591660
}
661+
}
592662
```
593663

594-
Now within the TodoStore callback we can explicitly wait for any dependencies to first update before moving forward. However, if Store A waits for Store B, and B waits for A, then a circular dependency will occur. A more robust dispatcher is required to flag this scenario with warnings in the console.
664+
Now within the store's callback we can explicitly wait for any dependencies to first update before moving forward. However, if Store A waits for Store B, and B waits for A, then a circular dependency will occur. To help prevent this situation, the dispatcher will throw an error in the brwoser console if we accidentally have two stores that are waiting for each other.
665+
595666

596667
The Future of Flux
597668
------------------

0 commit comments

Comments
 (0)