如何在Marrionette Composite View中为模型动态选择项目视图

时间:2016-01-29 16:36:51

标签: javascript backbone.js dynamic view marionette

我有一个模型,它有一个让我们称之为块的数组。所有块都具有块头属性。根据我具有哪种块头属性,我需要以不同的方式管理视图/模型。所以我想知道我可以在marrionette中使用复合或集合视图以何种方式渲染块集合,使用不同的模板,具体取决于每个模型中的块头。

我目前的工作是这样的:

App.view.external_report.TemplateSetup = Marrionette.CompositeView.extend({

  __name__: 'ExternalReport$TemplateSetup',
  template: 'external_report/templatesetup',
  className: 'external-report',
  super: App.view.CompositeView.prototype,
  id: 'template-setup',
  events: {

    'click #cancel': 'cancel',
    'click #save': 'save'

  },
  initialize: function(options) {

    if (!this.model || !this.model.get('template')) throw 'No model or template found';


    var templateObj = JSON.parse(this.model.get('template'));

    var blocks = templateObj.SubBlocks;

    this.blockViews = [];

    _.each(blocks, function(block) {

      var model = new Backbone.Model(block);

      this.blockViews.push(new App.view.external_report.blocks.BaseBlock({
        model: model
      }))

    }.bind(this));

  },

  onRender: function() {

    _.each(this.blockViews, function(blockView) {

      blockView.render().then(function() {

        this.$el.append(blockView.$el);

      }.bind(this));

    }.bind(this));

  },

  save: function() {

    this.model.set('template', JSON.stringify(this.generateTemplate()));

    this.model.save().then(function() {
      //placeholder
    }.bind(this));
  },


  generateTemplate: function() {

    var template = JSON.parse(this.model.get('template'));

    template.SubBlocks = [];

    _.each(this.blockViews, function(blockView) {

      template.SubBlocks.push(blockView.generateBlockJSON());

    }.bind(this));


    return template;

  }
});

1 个答案:

答案 0 :(得分:2)

我认为您应该创建两个ItemView并覆盖函数getChildView以选择要渲染的ItemView。

另一种方法是创建一个ItemView并选择要覆盖getTemplate函数的模板,以选择您要渲染的模板。