如何将模型插入特定索引中的backbone.js集合?

我需要在Collection.length-2位置的Collection中插入一个模型。 集合中的最后一个模型应该始终保持集合中的最后一个模型。

到目前为止我尝试了什么:

我在Collection“Pages”中添加了一个“页面”模型,然后尝试通过更改它们的顺序来交换它们:

var insertedpage = Pages.at(Pages.length-1); var lastpage = Pages.at(Pages.length-2); insertedpage.set({sequence: Pages.length-1}); lastpage.set({sequence: Pages.length}); 

我还尝试删除最后一页,然后添加一个新页面,然后重新添加最后一页。

 var lastpage = Pages.pop(); Pages.add({example1: example2}); Pages.push(lastpage); 

这些都不起作用。 新添加的页面仍显示为Collection中的最后一个模型。 在此之后我需要调用某种订单function吗?

对不起,简单回答(没时间回复),但请看定义比较器function。

http://backbonejs.org/#Collection-comparator

Backbone.Collection.add()接受一个options对象,该对象支持用于指定索引的at键。

传递{at: index}以将模型拼接到指定index处的集合中。

例:

 Pages.add({ foo: bar }, { at: Pages.length - 2 }) 

与Rob Hruska一样的建议atoptions对象中使用带有at Backbone.Collection.add()

 Pages = new Backbone.Collection([ {id:1, foo:'bar'}, {id:2, foo:'barista'} /* Last model should remain last */ ]); /* Insert new "page" not at the end (default) but length minus 1 */ Pages.add({id:3, foo:'bartender'}, { at: Pages.length - 1 }); Pages.at(0).id === 1; // true Pages.at(Pages.length - 2).id === 3; // true Pages.at(Pages.length - 1).id === 2; // true 

您提到Pages似乎按属性sequence ; 你碰巧在Pages集合上定义了comparator函数吗?

另一个问题,当您将新页面添加到第二个位置时,是否要在当前集合中的所有现有页面模型上更新此属性sequence ? 或者那个属性试图完成你原来的问题?