2014-12-02 61 views
0
Collection.fetch().done(function(){ 
    console.log(Collection); // fetchs all the models and successfully print here 

    Collection.localStorage = new Backbone.LocalStorage('Localstorage'); 
    console.log(localStorage); // Storage {length: 0} 
}); 

上面的代碼是獲取從以.json文件中的數據和創建模型,甚至成功地打印出它的console.log。取模型,並將其存儲localStorage的骨幹

但我甚至不得不將它存儲在LOCALSTORAGE,因爲當我在控制檯打印localstorage它顯示爲空。

我想是在頁面加載得到以.json文件中使用和存儲這些車型在localStorage的數據,以便下一次我會從localStorage的沒有從文件讀取數據(即模型)。

+0

你說的是設備本地存儲然後嘗試localStorage.a =「值」(如JSON字符串) – 2014-12-02 09:57:38

+0

燁,將工作,我如何做到這一點,同時使用取動作,因此,無論數據我將獲得取從JSON文件將得到存儲在本地存儲 – 2014-12-02 10:01:48

+0

如果它的集合你想保存然後做它作爲localStorage.coll = JSON.stringify(集合);並可以得到localStorage.coll whwn需要(只是解析它) – 2014-12-02 10:03:48

回答

0

您需要重寫集合的sync函數以放置邏輯中,以首先檢查緩存,然後從遠程位置讀取並更新緩存,以便後續請求將拾取緩存。

var Collection = Backbone.Collection.extend({ 
    sync: function(method, collection, options) { 
    var cache, data, dfd = $.Deferred(), 
     cacheId = "collectionCache"; 

    switch (method) { 
     case "read": 

     // Attempt to get the cache 
     cache = sessionStorage.getItem(cacheId); 

     // Check if the cache has anything 
     if (cache) { 
      console.log("Returning from cache"); 

      // If the cache exists, call the success callback and resolve the Deferred object 
      options.success(cache); 
      dfd.resolve(cache) 
     } else { 
      console.log("Returning from external data"); 

      // We would perform the ajax call here to fetch our JSON 
      data = externalData 

      // Set the data that came from the file into our session storage 
      sessionStorage.setItem(cacheId, data); 

      // Call the success callback and resolve the Deferred object with the data loaded from the file 
      options.success(data); 
      dfd.resolve(data); 
     } 
     break; 
    } 

    // By overriding the sync function for this collection, you would also have to define logic for the create, update and destory methods. 

    return dfd.promise(); 
    } 
}); 

請記住,當你重寫一個模型或集合的同步方法,你還必須編寫邏輯來處理,將要使用的其他方法,如createupdatedestroy。有關sync方法

更多信息可以在Backbone's Docs

我也把一個小提琴演示該功能被發現。 http://jsbin.com/hazimi/1/edit?js,console