You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
53
64
54
65
```javascript
55
-
varPromise=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).
57
70
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.
'Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.'
106
+
);
107
+
this._startDispatching(payload);
108
+
try {
109
+
for (var id inthis._callbacks) {
110
+
if (this._isPending[id]) {
111
+
continue;
112
+
}
113
+
this._invokeCallback(id);
114
+
}
115
+
} finally {
116
+
this._stopDispatching();
117
+
}
99
118
}
100
-
});
101
119
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 inthis._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
+
}
103
143
```
104
144
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.
106
146
107
147
Now we are all set to create a dispatcher that is more specific to our app, which we'll call AppDispatcher.
108
148
@@ -130,7 +170,9 @@ var AppDispatcher = merge(Dispatcher.prototype, {
130
170
module.exports= AppDispatcher;
131
171
```
132
172
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.
134
176
135
177
136
178
Creating Stores
@@ -372,7 +414,7 @@ Text input, on the other hand, is just a bit more complicated because we need to
372
414
373
415
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.
374
416
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.
376
418
377
419
```javascript
378
420
/** @jsx React.DOM */
@@ -497,10 +539,10 @@ module.exports = Header;
497
539
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.
498
540
499
541
500
-
Creating Semantic Actions
501
-
-------------------------
542
+
Creating Actions with Semantic Methods
543
+
--------------------------------------
502
544
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:
504
546
505
547
```javascript
506
548
/**
@@ -571,27 +613,56 @@ React.renderComponent(
571
613
);
572
614
```
573
615
574
-
Adding Dependency Management to the Dispatcher
616
+
Dependency Management in the Dispatcher
575
617
----------------------------------------------
576
618
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.
578
620
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:
580
622
581
623
```javascript
582
-
/**
583
-
* @param{array}promisesIndexes
584
-
* @param{function}callback
585
-
*/
586
-
waitFor:function(promiseIndexes, callback) {
587
-
var selectedPromises =promiseIndexes.map(function(index) {
// 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);
591
660
}
661
+
}
592
662
```
593
663
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.
0 commit comments