我可以将Marionette集合视图附加到现有HTML吗?

时间:2014-01-20 02:42:33

标签: javascript backbone.js collections views marionette

我正在使用带有node的browserify来渲染服务器上的集合,然后在客户端使用Marionette。

是否可以使用Marionette区域attachView()将CollectionView附加到现有的html列表中?

2 个答案:

答案 0 :(得分:3)

Marionette没有提供通过标准API执行此操作的方法,但可以使用Marionette的一些内部CollectionView方法。我在这里提供了一个例子:

http://jsbin.com/zirupeli/1/edit

关键部分是CollectionView中的createChildren函数:

var List = Marionette.CollectionView.extend({
  el: 'ul',

  itemView: Item,

  initialize: function() {
    this.createChildren();
  },

  createChildren: function() {
    this.collection.each(function(model) {
      var view = new this.itemView({
        el: 'li:eq(' + (model.get('id') - 1) + ')',
        model: model
      });

      // set up the child view event forwarding
      this.addChildViewEventForwarding(view);

      // Store the child view itself so we can properly
      // remove and/or close it later
      this.children.add(view);
    }, this);
  }
});

在这里,我们只为集合中的每个项目创建ItemView,然后调用两个内部Marionette CollectionView方法:this.addChildViewEventForwardingthis.children.add。 Marionette在呈现子视图时会在内部使用它们:

https://github.com/marionettejs/backbone.marionette/blob/master/lib/backbone.marionette.js#L1687

为了证明这是正常的,在四秒钟之后您应该注意到一个项目被添加到列表中,并且在八秒钟之后,列表中的第一个项目被删除。

答案 1 :(得分:0)

自版本2.0.0起,addChildViewEventForwarding函数已被删除。

替换...

this.addChildViewEventForwarding(view);

使用...

this.proxyChildEvents(view);

我知道,我也更愿意评论@StephenYoung提供的答案,但我没有声誉。仍然是一个padawan。

相关问题