如何将子视图生命周期职责移至 Marionette

How to move subviews lifecycle responsibilities to Marionette

问题 如何将子视图生命周期职责从MyView移动到Marionette? (见下面的代码)

这里的问题是 items 数组是在服务器上动态形成的,我不想在 MyView 中遍历它们。我需要 Marionette.CollectionView 吗?

代码:

我有my-view.hbs模板:

{{#each items}}
  <button class="button">name</button>
  <div name="target"/>  <!-- each target div should contain a subview -->
{{/each}}

以及渲染它的视图:

var MyView = Marionette.LayoutView.extend({
  template: Templates['my-view.hbs'],

  render: function() {
    var items = [ //actually they come from server
      {name: 'car'},
      {name: 'bike'},
      {name: 'skiboard'},
    ];
    this.$el.html(
      this.template({ items: items })
    );
    this.renderSubViews();
    return this;
  },
  /**
   * It creates, renders and append subViews manually.
   * TODO: move responsibilities to Marionette
   */
  renderSubViews: function() {
    var self = this;
    self.subViews = [];
    self.$('div[name=target]').each(function(index, subViewContainer) {
      var subView = new SubView();
      self.subViews.add(subView);
      subView.render();
      $(subViewContainer).append(subView.$el);
    });
  }
});

如果短,是的,你需要CompositeCollectionView。 此外,我建议您使用 Collection 而不是普通对象,它将帮助您更轻松地在数据(模型)和您的视图之间进行通信:

var ItemModel = Backbone.Model.extend({
        defaults: {
            name: 'unnamed'
        }
    }), 
    ItemsCollection = Backbone.Collection.extend({
        model: ItemModel
    }),

    MyChildView = Marionette.ItemView.extend({
        template: Templates['my-view.hbs']
    }),
    MyView = Marionette.CollectionView.extend({
        childView: MyChildView,
        collection: new ItemsCollection([
            {name: 'car'},
            {name: 'bike'},
            {name: 'skiboard'}
        ])
    });

您的模板也会更简单:

<button class="button">name</button>
<div name="target"/>