如何使用循环创建多个主干视图?

时间:2016-06-08 18:21:25

标签: javascript backbone.js

我有一个实例多个选择视图的方法,在这些实例中唯一真正改变的是传入的模型属性。使用循环创建这些是一个很好的解决方案实例,这些数字可以增长或者是什么建议?

JS

setSelects: function(model) {

    if(this.sessionSelect) {
        this.sessionSelect.dispose();
    }
    this.sessionSelect = new SearchInputsView({
        options: model.get('sessions'),
        name: 'sessionId'
    });
    this.$('label[for=sessionId]').append(this.sessionSelect.render().el);

    if(this.accountSelect) {
        this.accountSelect.dispose();
    }
    this.accountSelect = new SearchInputsView({
        options: model.get('accountRestrs'),
        name: 'account'
    });
    this.$('label[for=account]').append(this.accountSelect.render().el);

    if(this.tagFifty) {
        this.tagFifty.dispose();
    }
    this.tagFifty = new SearchInputsView({
        options: model.get('tag50Restrs'),
        name: 'tag50'
    });
    this.$('label[for=tag50]').append(this.tagFifty.render().el);
},

1 个答案:

答案 0 :(得分:2)

var Subviews= [ { 
                  subview: "tagFifty",
                  el:"label[for=tag50]",
                  model:'tag50Restrs'},
                },
                { ... } 
              ]

_.each(Subviews, function(subview) {
  // switch here + use of params
});

下面是我自己代码的示例:

   renderSubview: function(options) {
        this.clearScreen();
        this.subviewName = options.subview;

        switch(options.subview) {
            case 'home':
                var homeView = new HomeView();
                homeView.inAnimation();
                this.subview = homeView;
                break;
            case 'rdv':
                var rdvView = new RdvView();
                rdvView.inAnimation();
                this.subview = rdvView;
                break;
            case 'destinations':
                var destinationsView = new DestinationsView(options);
                destinationsView.inAnimation();
                this.subview = destinationsView;
                break;
        }
    },