我正在尝试了解 Reflux 操作和存储的工作原理,因此我编写了一个小型测试程序。当我运行应用程序时,调用的代码
toggleGem();
(这会导致 Reflux Action 触发)不会立即运行。这些动作事件被排队,如下程序的输出所示。
输出是:
myObj=lastUpdate=undefined
myObj=lastUpdate=undefined
myObj=lastUpdate=undefined
ENTER: gemStore.handleToggleGem: isGemActivated:false
MyObj.onGemChange: newVal=true
EXIT: gemStore.handleToggleGem: isGemActivated:true
ENTER: gemStore.handleToggleGem: isGemActivated:true
MyObj.onGemChange: newVal=false
EXIT: gemStore.handleToggleGem: isGemActivated:false
注意控制台输出
ENTER: gemStore.handleToggleGem: isGemActivated:false
在程序退出之前不会出现。这(对我来说)意味着动作事件被 Reflux 正在做的一些“内务处理”捆绑和触发/运行。
我可以调用一个函数来告诉 Reflux 触发已排队的操作事件吗?
要重新创建此示例,只需将代码保存到 RefluxTest.js 并运行以下命令:
mkdir RefluxTest
npm init
npm install --save reflux
npm install --save react
node RefluxTest.js
谢谢。
注意:我知道这并不代表 Reflux 通常如何使用,因为它在浏览器之外,但我很好奇是否有人有答案。
基于来自http://spoike.ghost.io/deconstructing-reactjss-flux/的代码
// Code for file RefluxTest.js
// KWS: Learning how Reflux works outside of the browser
var React = require("react/addons");
var TestUtils = React.addons.TestUtils;
var Reflux = require("reflux");
// Creating action
var toggleGem = Reflux.createAction();
// Creates a DataStore
var gemStore = Reflux.createStore({
// Initial setup
init: function() {
this.isGemActivated = false;
// Register statusUpdate action
this.listenTo(toggleGem, this.handleToggleGem);
},
// Callback
handleToggleGem: function() {
console.log('ENTER: gemStore.handleToggleGem: isGemActivated:' + this.isGemActivated);
this.isGemActivated = !this.isGemActivated;
// Pass on to listeners through
// the DataStore.trigger function
this.trigger(this.isGemActivated);
console.log('EXIT: gemStore.handleToggleGem: isGemActivated:' + this.isGemActivated);
}
});
function MyObj() {
gemStore.listen(this.onGemChange);
this.lastUpdate = undefined;
}
MyObj.prototype.toString = function() {
return "lastUpdate=" + this.lastUpdate;
}
MyObj.prototype.onGemChange = function(newVal){
console.log("MyObj.onGemChange: newVal=" + newVal);
this.lastUpdate = newVal;
}
var myObj = new MyObj();
console.log("myObj=" + myObj);
toggleGem();
console.log("myObj=" + myObj);
toggleGem();
console.log("myObj=" + myObj);