【问题标题】:How to dynamically choose Item Views for models in Marrionette Composite View如何在 Marrionette Composite View 中为模型动态选择项目视图
【发布时间】:2016-01-29 16:36:50
【问题描述】:

我有一个模型,其中包含一组让我们称之为块的模型。所有块都有一个块头属性。根据我拥有的块头属性,我需要以不同的方式管理视图/模型。所以我想知道我可以用什么方式在木偶中使用复合视图或集合视图来渲染块集合,根据每个模型中的块头使用不同的模板。

我目前的工作是这样的:

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;

  }
});

【问题讨论】:

标签: javascript backbone.js dynamic view marionette


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2014-01-25
    相关资源
    最近更新 更多