Created
December 2, 2012 22:25
-
-
Save marteinn/4191329 to your computer and use it in GitHub Desktop.
Backbone.js + Local Connection cache example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /*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