javascript - 如何将 subview 生命周期责任移至 Marionette

标签 javascript backbone.js marionette

问题 如何将 subview 生命周期职责从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}}

以及渲染它的 View :

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);
    });
  }
});

最佳答案

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

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"/>

关于javascript - 如何将 subview 生命周期责任移至 Marionette,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30053246/

相关文章:

backbone.js - requirejs 文本插件下载所有不需要的模板

javascript - 没有从 appRouter 调用 Backbone Marionette Controller 方法

javascript - 如何使用 requirejs 覆盖 vendor 库

javascript - 主干 - 未为模型定义 model.destroy() 函数

javascript - 当 'click' 事件存在时,BackboneJS 'focusout' 事件不会触发

javascript - Marionette:检查布局是否有另一个对象的实例

javascript - 检查父 div 中是否有 <select>

Javascript 清除监听器和变量

javascript - NodeJS 脚本作为 Windows 服务运行。无法写入文件

javascript - MongoDB - 使用范围查询进行分页