0

我想將模型添加到將通過Backbone.localstorage插件存儲在本地存儲中的集合。將模型添加到Backbone.localstorage集合

集合中添加模型的代碼如下:

define([ 'jquery', 'underscore', 'model/articleModel', 'backbone', 'localstorage' ],  function($, _, itsModel, Backbone) { 
    var articleCache = Backbone.Collection.extend({ 
     model: itsModel, 
     localStorage: new Backbone.LocalStorage("articles-backbone-cache"), 

     addArticle: function(model){ 
      console.log('Adding new article ID [' + model.id + '] Title [' + model.title  + '] to cache via backbone.localstorage'); 
      console.log(model); 

      //CRUCIAL PART 
      this.create(model); // Doesn't work 
      this.create(model.toJSON()); //Doesn't work 
      this.create({id: model.id}); // Works but only id is saved and naturally all other attributes are set to defaults 
     } 
    }); 

    return articleCache; 
}); 

的模型是:

define([ 'jquery', 'underscore', 'backbone', 'localstorage' ], function($, _, Backbone) { 

    var article = Backbone.Model.extend({ 
     defaults : { 
      id : '0', 
      title : '', 
      subtitile : '', 
      date : '', 
      section : '', 
      section_id : -1, 
      subsection : null, 
      subsection_id : null, 
      noOfComments : 0 
    }); 

    return article; 
}); 

的問題是,該模型沒有被保存到本地存儲。它只保存到本地存儲當我使用「this.create({id:model.id});」但缺少所有其他屬性。

傳遞給addArticle(model)的模型與它期望的模型相同,任何人都可以提供一些關於如何將這些數據存儲到本地存儲的幫助?

我不想寫下面的,因爲它已經在該形式:

this.create({id: model.id, title:model.title, . . . }) 
+0

確保您的所有模型都有ID和不同的ID。 – 2014-10-07 16:52:12

+0

檢查並檢查。我試圖保存到該集合的模型是使用普通骨幹REST調用從遠程服務器檢索的。所以所有的id都是唯一的,非空/未定義的。 – 2014-10-07 17:00:41

回答

0

使用add而不是create

http://backbonejs.org/#Collection-createcollection.create(attributes, [options])

http://backbonejs.org/#Collection-addcollection.add(models, [options])

+0

我曾嘗試使用添加,那也不起作用。另外,根據[here](http://backbonejs.org/docs/todos.html),創建方法應該用於本地存儲插件。編輯:使用add()在原始問題中概述的所有3種情況下都失敗。 – 2014-10-07 17:18:16

+0

你可以創建一個小提琴來玩。 – 2014-10-07 17:23:47

0

要添加模型到集合,你應該使用add函數。

這會將模型添加到集合中,但同步不會發生在localStorage上。

要將增加的模型保留到localStorage,您必須致電model.save()

HTH!