提问者:小点点

如何在万豪综合视图中动态选择模型的项目视图


我有一个模型,它有一个数组,让我们称之为块。所有块都具有块标题属性。根据我拥有的块标题属性,我需要以不同的方式管理视图/模型。因此,我想知道如何使用marrionette中的composite或collection视图渲染块集合,根据每个模型中的块标题使用不同的模板。

我目前的工作是这样的:

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个答案

匿名用户

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

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