在flux体系结构中,谁负责向服务器发送更新?

时间:2014-11-08 12:01:19

标签: javascript architecture single-responsibility-principle reactjs-flux

因此,在通量架构中,数据流如下:

View -> Action -> Dispatcher -> Store
 ^ <-----------------------------|

所以,让我们说视图是一个评论框。当用户提交注释时,会触发addComment操作,但该注释应该在何处发送到服务器?它应该在动作函数中发生,在发送之前,还是商店在收到调度员的动作时是否应该这样做?

这两种情况都像是违反单一责任模式。或者是否应该有两个CommentStore,一个LocalCommentStore和一个ServerCommentStore都处理addComment操作?

2 个答案:

答案 0 :(得分:6)

在您的情况下,Action负责向商店发送待处理操作或乐观更新并向WebAPI发送调用:

View -> Action -> Pending Action or optimistic update  -> Dispatcher -> Store -> emitEvent -> View 
               -> WebUtils.callAPI()

onWebAPISuccess -> Dispatcher -> Store -> emitEvent -> View
onWebAPIFail -> Dispatcher -> Store -> emitEvent -> View

答案 1 :(得分:4)

这是一个很好的问题。我就是这样做的。

我为我的API创建了一个模块。我在actions.js中导入该模块,然后将API响应发送到我的商店。下面是我的应用程序中API调用的商店可能如下所示的示例(使用fluxxor):

# actions.js
var MyAPI = require('./my-api'),
    Constants = require('./constants/action-constants');

module.exports = {
    doSomeCrazyStuff: function(stuff, userID) {
        MyAPI.doSomeCrazyStuff(stuff, userID)
             .success(function(resp) {
                 this.dispatch(Constants.DO_CRAZY_STUFF_SUCCESS, {stuff: resp.stuff});
                 if (resp.first_stuff_did) {
                     this.dispatch(Constants.SHOW_WELCOME_MESSAGE, {msg: resp.msg});
                 }
             })
             .error(function(e) {
                 this.dispatch(Constants.DO_CRAZY_STUFF_ERROR, {e: resp.error});
             });
    }
};

# store.js
var Fluxxor = require('fluxxor'),
    ActionConstants = require('./constants/action-constants');

var StuffStore = module.exports = {
    Fluxxor.createStore({
        initialize: function() {
            this._bindActions();
            this.stuff = null;
        },
        _bindActions: function() {
            this.bindActions(
                ActionConstants.DO_CRAZY_STUFF_SUCCESS, this.handleDoCrazyStuffSuccess
            );
        },
        handleDoCrazyStuffSuccess: function(payload) {
            this.stuff = payload.stuff;
            this.emit('change');
        }
   });
}

# stuff-component.js
var React = require('react'),
    Fluxxor = require('fluxxor'),
    FluxMixin = Fluxxor.FluxMixin(React),
    StoreWatchMixin = Fluxxor.storeWatchMixin;

var StuffComponent = module.exports = React.createClass(function() {
    mixins: [FluxMixin, StoreWatchMixin("StuffStore")],
    getStateFromFlux: function() {
        flux = this.getFlux();

        var StuffStore = flux.store("StuffStore").getState();

        return {
            stuff: StuffStore.stuff
        }
    },
    onClick: function() {
        this.getFlux().actions.doSomeCrazyStuff();
    },
    render: function() {
        return <div onClick={this.onClick}>{this.state.stuff}</div>
    }
});