七、Store
Store 保存整个应用的状态。它的角色有点像 MVC 架构之中的Model 。
在我们的 Demo 中,有一个ListStore
,所有数据都存放在那里。
// 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 监听到这个事件,就可以查询新的状态,更新页面了。