我正在使用Backbone.Marionette的CompositeView,我想在集合的索引0处插入一个新模型,并将其显示为复合中的第一个视图。
我有这个代码来插入元素:
PlansApp.Plans.collection.unshift new PlansApp.Plan data
问题是CompositeView忽略了集合中新插入项的索引。
在Backbone.Marionette中,appendHtml方法如下所示:
appendHtml: function(collectionView, itemView, index){
collectionView.$el.append(itemView.el);
},
从不使用index参数。
新插入的视图将始终放在合成的末尾。
如何让它出现在0位?
答案 0 :(得分:3)
这是设计上的,因为在直接支持已排序集合中已识别出边缘案例的数量。
添加了index
参数,以便开发人员可以在其应用程序中单独添加支持。有一个wiki页面,显示了如何执行此操作的示例:https://github.com/derickbailey/backbone.marionette/wiki/Adding-support-for-sorted-collections
MySortedView = Backbone.Marionette.CompositeView.extend({
// ...,
appendHtml: function(collectionView, itemView, index){
var childrenContainer = $(collectionView.childrenContainer || collectionView.el);
var children = childrenContainer.children();
if (children.size() === index) {
childrenContainer.append(itemView.el);
} else {
childrenContainer.children().eq(index).before(itemView.el);
}
}
});
答案 1 :(得分:0)
Derick的原始答案对于当前版本的Marionette来说有点过时了,而wiki只包含了一个集合视图的示例。
这是我目前用于复合视图的内容:
appendHtml: (collectionView, itemView, index) ->
$container = @getItemViewContainer(collectionView)
if index is 0
$container.prepend itemView.el
else
childAtIndex = $container.children().eq(index)
if childAtIndex.length
childAtIndex.before itemView.el
else
$container.append itemView.el