[英]How do I insert a model into a backbone.js collection in a specific index?
I need to insert a model into a Collection at position Collection.length-2. 我需要在Collection.length-2位置的Collection中插入一个模型。 The last model in the collection should always stay the last model in the collection. 集合中的最后一个模型应该始终保持集合中的最后一个模型。
What I tried so far: 到目前为止我尝试了什么:
I added one "page" model to the Collection "Pages" and then tried to swap them around by changing their sequence: 我在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});
I also tried to remove the last page, then add a new page and then add the last page back in. 我还尝试删除最后一页,然后添加一个新页面,然后重新添加最后一页。
var lastpage = Pages.pop();
Pages.add({example1: example2});
Pages.push(lastpage);
neither of these worked. 这些都不起作用。 The newly added page still appears as last model in the Collection. 新添加的页面仍显示为Collection中的最后一个模型。 Do I need to call some kind of order function after this? 在此之后我需要调用某种订单功能吗?
Backbone.Collection.add()
takes an options
object that supports an at
key for specifying the index. Backbone.Collection.add()
接受一个options
对象,该对象支持用于指定索引的at
键。
Pass
{at: index}
to splice the model into the collection at the specifiedindex
. 传递{at: index}
以将模型拼接到指定index
处的集合中。
Example: 例:
Pages.add({ foo: bar }, { at: Pages.length - 2 })
Along the same suggestion as Rob Hruska, use Backbone.Collection.add()
with at
in the options
object. 与Rob Hruska一样的建议at
在options
对象中使用带有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
You mentioned that Pages
seems to be sorted by the attribute sequence
; 您提到Pages
似乎按属性sequence
; do you happen to have a comparator
function defined on the Pages collection? 你碰巧在Pages集合上定义了comparator
函数吗?
Another question, did you want to update this attribute sequence
on ALL existing page models currently in the collection when a new page is added to the 2nd to the last position? 另一个问题是,当新页面添加到第二个位置时,是否要更新当前集合中所有现有页面模型的此属性sequence
? Or was that attribute an attempt to accomplish your original question? 或者那个属性试图完成你原来的问题?
Sorry for the brief answer (don't have time to respond), but look at defining a comparator function. 对不起,简单回答(没时间回复),但请看定义比较器功能。
http://backbonejs.org/#Collection-comparator http://backbonejs.org/#Collection-comparator
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.