Backbone.js - 协调布局(实例化),状态和历史

时间:2011-10-19 13:45:38

标签: javascript model-view-controller backbone.js state

我正在寻找一种简单且可扩展的方法来序列化我的Backbone.js应用程序的完整状态。

假设我想在我的“GlobalStateModel”中存储完整状态(某些小部件模型+元信息,例如应用程序的布局等):

var GlobalStateModel = Backbone.Model.extend({
    defaults : {
        layout : undefined,
        widgetType1Collection : undefined, //Widget models
    },
}); 

我想这样做,因为我可以轻松设置相应的历史记录条目:

var HistoryController = Backbone.View.extend({
    model : globalStateModel,

    initialize: function () {   
        _.bindAll(this, "render", "updateHistory");
        this.model.bind("change", this.updateHistory);  
    },

    updateHistory : function () {
        var globalStateModel = this.model.toJSON()
        var state = jQuery.param.querystring("", state )
        appRouter.navigate('v1' + state, false);
    }
});

但是这里有一个棘手的部分...我想要一个LayoutController或类似的实例化与上面一起工作的widget模块:

var LayoutController = Backbone.View.extend({   
    initialize: function () {   
        _.bindAll(this, "render");
        this.model.bind("change:layout", this.render);      
    },

    render : function () {
        var layout = this.model.get("layout");

        switch(layout){
            case "layout-1":
            this.renderLayout1();
            break;

            case "layout-2":
            this.renderLayout2();
            break;
        }
    },

    renderLayout1 : function () {       

        var widgetModel1 = new WidgetModel()
        var widgetController1 = new WidgetController({model : widgetModel1})

        this.model.widgetType1Collection.add(widgetModel1);

        //fetch the right widget model attributes from the global state?
        widgetAttrs = { ..... }
        widgetModel1.set(widgetAttrs)

     },

});

也许这种方法存在完全缺陷,或者我可能只是缺少一些管道来实现这一点?

如何使LayoutController实例化1个或多个小部件并让其模型成为globalState的一部分?

这样1)当他们的模型/集合发生变化时,globalState被正确序列化; 2)globalState changes / hashchanges在小部件中得到正确反映?

0 个答案:

没有答案