![](/img/trans.png)
[英]In Backbone.js, after I 'create' a model under a collection, how do I update that model?
[英]How do I insert a model into a backbone.js collection in a specific index?
我需要在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中的最后一個模型。 在此之后我需要調用某種訂單功能嗎?
Backbone.Collection.add()
接受一個options
對象,該對象支持用於指定索引的at
鍵。
傳遞
{at: index}
以將模型拼接到指定index
處的集合中。
例:
Pages.add({ foo: bar }, { at: Pages.length - 2 })
與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
您提到Pages
似乎按屬性sequence
; 你碰巧在Pages集合上定義了comparator
函數嗎?
另一個問題是,當新頁面添加到第二個位置時,是否要更新當前集合中所有現有頁面模型的此屬性sequence
? 或者那個屬性試圖完成你原來的問題?
對不起,簡單回答(沒時間回復),但請看定義比較器功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.