Skip to content

Instantly share code, notes, and snippets.

@marteinn
Created December 2, 2012 22:25
Show Gist options
  • Select an option

  • Save marteinn/4191329 to your computer and use it in GitHub Desktop.

Select an option

Save marteinn/4191329 to your computer and use it in GitHub Desktop.
Backbone.js + Local Connection cache example
/*global require, define, console, Modernizr */
define([
"jquery",
"backbone"
], function ($, Backbone) {
var storage = {};
if (Modernizr.localstorage) {
storage = window.localStorage;
}
var cache = {
get : function (key) {
return storage[key];
},
set : function (key, value) {
return storage[key] = value;
},
has : function (key) {
return storage[key] !== undefined;
},
remove : function (key) {
delete storage[key];
}
};
var sync = Backbone.sync;
Backbone.sync = function (method, model, options) {
var allowCache = options.cache || false;
var expires = options.cacheExpires || 60*60;
var hasCache;
var expireDate = 0;
var url;
var success;
var data;
// TODO: Add cache name id support
if (method === "read" && allowCache) {
success = options.success;
url = model.url();
hasCache = cache.has(url);
if (hasCache) {
expireDate = Number(cache.get("expires:"+url));
}
// Restore from cache
if (hasCache && expireDate>new Date().getTime()) {
data = cache.get(url);
options.success(cache.get(url), "success");
return $.ajax();
// Save to cache
} else {
options.success = function (resp, status, xhr) {
expireDate = new Date().getTime()+(expires*1000);
cache.set("expires:"+url, expireDate);
cache.set(url, resp);
success(resp, status, xhr);
};
}
}
return sync.apply(Backbone, arguments);
};
return cache;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment