## 七、Store
Store 保存整個應用的狀態。它的角色有點像 MVC 架構之中的Model 。
在我們的 Demo 中,有一個[`ListStore`](https://github.com/ruanyf/extremely-simple-flux-demo/blob/master/stores/ListStore.js),所有數據都存放在那里。
> ~~~
> // stores/ListStore.js
> var ListStore = {
> items: [],
>
> getAll: function() {
> return this.items;
> },
>
> addNewItemHandler: function (text) {
> this.items.push(text);
> },
>
> emitChange: function () {
> this.emit('change');
> }
> };
>
> module.exports = ListStore;
> ~~~
上面代碼中,`ListStore.items`用來保存條目,`ListStore.getAll()`用來讀取所有條目,`ListStore.emitChange()`用來發出一個"change"事件。
由于 Store 需要在變動后向 View 發送"change"事件,因此它必須實現事件接口。
> ~~~
> // stores/ListStore.js
> var EventEmitter = require('events').EventEmitter;
> var assign = require('object-assign');
>
> var ListStore = assign({}, EventEmitter.prototype, {
> items: [],
>
> getAll: function () {
> return this.items;
> },
>
> addNewItemHandler: function (text) {
> this.items.push(text);
> },
>
> emitChange: function () {
> this.emit('change');
> },
>
> addChangeListener: function(callback) {
> this.on('change', callback);
> },
>
> removeChangeListener: function(callback) {
> this.removeListener('change', callback);
> }
> });
> ~~~
上面代碼中,`ListStore`繼承了`EventEmitter.prototype`,因此就能使用`ListStore.on()`和`ListStore.emit()`,來監聽和觸發事件了。
Store 更新后(`this.addNewItemHandler()`)發出事件(`this.emitChange()`),表明狀態已經改變。 View 監聽到這個事件,就可以查詢新的狀態,更新頁面了。