您需要重寫集合的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();
}
});
請記住,當你重寫一個模型或集合的同步方法,你還必須編寫邏輯來處理,將要使用的其他方法,如create
,update
和destroy
。有關sync
方法
更多信息可以在Backbone's Docs
我也把一個小提琴演示該功能被發現。 http://jsbin.com/hazimi/1/edit?js,console
你說的是設備本地存儲然後嘗試localStorage.a =「值」(如JSON字符串) – 2014-12-02 09:57:38
燁,將工作,我如何做到這一點,同時使用取動作,因此,無論數據我將獲得取從JSON文件將得到存儲在本地存儲 – 2014-12-02 10:01:48
如果它的集合你想保存然後做它作爲localStorage.coll = JSON.stringify(集合);並可以得到localStorage.coll whwn需要(只是解析它) – 2014-12-02 10:03:48