如何在BackboneJS * marionette * collectionView中打印行线?

时间:2012-08-12 10:31:22

标签: javascript backbone.js marionette

我有一个使用LI itemView创建UL的collectionView。

我想在下划线模板中使用项索引号(count)。即:

hello (item 0)
world (item 1)

有人知道如何使用牵线木偶计数吗? 我想避免把它放在模型中。

这就是我希望我的itemView模板看起来像(项目数为n):

<script id="task-template" type="text/html">
          <div class="order"><%=n%></div>
          <div class="title-container">
               <a href="#">...</a>
          </div>
 </script>

任何帮助表示赞赏,

欢呼声,

2 个答案:

答案 0 :(得分:9)

我刚刚找到了一种简单的方法。 (使用Marionette v1.0.0-rc6)

使用 templateHelpers 属性。

在商品视图中:

MyItemView = Backbone.Marionette.ItemView.extend({
    template: "#my-item-view-template",

    templateHelpers: function(){

        var modelIndex = this.model.collection.indexOf(this.model);
        return {
            index: modelIndex
        }

    }
});

在模板中,您可以使用以下方法打印索引:

<%= index %>

就是这样。

答案 1 :(得分:3)

这应该很简单,因为集合中的模型可以轻松获取所需的信息。您需要在模型周围创建一个“视图模型”包装器,以便您可以获取所需的额外信息。


var createViewModel(model){

  // inherit from the original model
  var vm = Object.create(model);

  // override the original `toJSON` method
  vm.toJSON = function(){
    var json = model.toJSON();

    // add the index
    json.index = model.collection.indexOf(model);

    return json;
  }

  return vm;
}

您的itemView将直接使用此视图模型。


MyItemView = Backbone.Marionette.ItemView.extend({
  template: "#my-item-view-template",

  initialize: function(){

    // replace the model with the the view model
    this.model = createViewModel(this.model);

  }
});

MyCollectionView = Backbone.Marionette.CollectionView({
  itemView: MyItemView
});

就是这样。

将集合传递给MyCollectionView构造函数并渲染集合视图时,将在实例化itemView时为每个itemView实例创建新的视图模型。模板现在可以从模型中呈现index

视图模型直接从原始模型继承,因此所有方法和属性仍然可用。覆盖toJSON方法允许您从原始模型中获取原始json,然后使用您需要的任何数据对其进行扩充。您的原始模型永远不会被修改,但项目视图正在使用的模型具有您需要的数据。