[英]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.