How do I insert a model into a backbone.js collection in a specific index?

后端 未结 3 1562
逝去的感伤
逝去的感伤 2020-12-14 19:01

I need to insert a model into a Collection at position Collection.length-2. The last model in the collection should always stay the last model in the collection.

Wh

3条回答
  •  天涯浪人
    2020-12-14 19:23

    Along the same suggestion as Rob Hruska, use Backbone.Collection.add() with at in the options object.

    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; do you happen to have a comparator function defined on the Pages collection?

    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? Or was that attribute an attempt to accomplish your original question?

提交回复
热议问题