请参阅 Sophie 在处理异步数据的这个fluxxor 示例中解释的实现。不利的一点是,按照这种方法,每个用户交互都需要三个动作(触发、成功和失败),但可能并非所有用户交互都需要这种乐观的方法。
重要的部分是在行动中:
loadBuzz: function() {
this.dispatch(constants.LOAD_BUZZ);
BuzzwordClient.load(function(words) {
this.dispatch(constants.LOAD_BUZZ_SUCCESS, {words: words});
}.bind(this), function(error) {
this.dispatch(constants.LOAD_BUZZ_FAIL, {error: error});
}.bind(this));
},
BinaryMuse(fluxxor 创建者)调度 LOAD_BUZZ 动作,然后使用成功和失败函数触发异步请求,其中调度成功或失败动作。商店可以侦听 LOAD_BUZZ 操作以进行乐观更新或显示 svg 加载图标,然后侦听成功和错误操作以获取成功或错误的最终通知(加上将 BUZZWORD 保存在商店中)。
onLoadBuzz: function() {
this.loading = true;
this.emit("change");
},
onLoadBuzzSuccess: function(payload) {
this.loading = false;
this.error = null;
this.words = payload.words.reduce(function(acc, word) {
var clientId = _.uniqueId();
acc[clientId] = {id: clientId, word: word, status: "OK"};
return acc;
}, {});
this.emit("change");
},
我认为像 Sophie 一样,ajax 请求不应该阻止操作被分派,因为这更像是对服务器的同步请求,并且页面的响应性会受到影响。