## 六、Dispatcher
Dispatcher 的作用是將 Action 派發到 Store、。你可以把它看作一個路由器,負責在 View 和 Store 之間,建立 Action 的正確傳遞路線。注意,Dispatcher 只能有一個,而且是全局的。
Facebook官方的?[Dispatcher 實現](https://github.com/facebook/flux)輸出一個類,你要寫一個[`AppDispatcher.js`](https://github.com/ruanyf/extremely-simple-flux-demo/blob/master/dispatcher/AppDispatcher.js),生成 Dispatcher 實例。
> ~~~
> // dispatcher/AppDispatcher.js
> var Dispatcher = require('flux').Dispatcher;
> module.exports = new Dispatcher();
> ~~~
`AppDispatcher.register()`方法用來登記各種Action的回調函數。
> ~~~
> // dispatcher/AppDispatcher.js
> var ListStore = require('../stores/ListStore');
>
> AppDispatcher.register(function (action) {
> switch(action.actionType) {
> case 'ADD_NEW_ITEM':
> ListStore.addNewItemHandler(action.text);
> ListStore.emitChange();
> break;
> default:
> // no op
> }
> })
> ~~~
上面代碼中,Dispatcher收到`ADD_NEW_ITEM`動作,就會執行回調函數,對`ListStore`進行操作。
記住,Dispatcher 只用來派發 Action,不應該有其他邏輯。