[英]how can I have CollectionView of CollectionView in marionette.js?
[英]how can i print the row line in BackboneJS *marionette* collectionView?
我有一个使用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>
任何帮助赞赏,
干杯,
我刚刚找到了一个简单的方法。 (使用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 %>
就这样。
这应该很简单,因为集合中的模型可以轻松获取所需的信息。 您需要在模型周围创建一个“视图模型”包装器,以便您可以获取所需的额外信息。
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
构造函数并呈现集合视图时,将在实例化MyCollectionView
为每个itemView实例创建新的视图模型。 模板现在可以从模型中呈现index
。
视图模型直接从原始模型继承,因此所有方法和属性仍然可用。 覆盖toJSON
方法允许您从原始模型中获取原始json,然后使用您需要的任何数据对其进行扩充。 您的原始模型永远不会被修改,但项目视图正在使用的模型具有您需要的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.