簡體   English   中英

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

[英]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一樣的建議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 或者那個屬性試圖完成你原來的問題?

對不起,簡單回答(沒時間回復),但請看定義比較器功能。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM