[英]Fetch models from JSON.file and store it localstorage Backbone
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時,它顯示為空。
我想要的是在頁面加載中使用.json文件獲取數據並將這些模型存儲在Localstorage中,以便下次我將從本地存儲而不是從文件中獲取數據(即模型) 。
您將需要覆蓋集合的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();
}
});
請記住,當您覆蓋模型或集合的sync方法時,還必須編寫邏輯來處理將要使用的其他方法,例如create
, update
和destroy
。
有關sync
方法的更多信息,請參見Backbone的文檔
我還整理了一個小提琴來演示此功能。 http://jsbin.com/hazimi/1/edit?js,控制台
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.