-
-
Save boazsender/3532848 to your computer and use it in GitHub Desktop.
Backbone.Collection caching by URL
This file contains 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
/*! | |
* backbone.cache.js v0.0.2 | |
* Copyright 2012, Boaz Sender (@boazsender) | |
* Based on backbone.collectioncache.js by Tim Branyen (@tbranyen) (https://gist.github.com/gists/3532848/edit) | |
* backbone.cacher.js may be freely distributed under the MIT license. | |
*/ | |
(function(window) { | |
// Dependencies | |
var Backbone = window.Backbone; | |
var _ = window._; | |
var $ = window.$; | |
// If session doesn't exist, simply use a plain object. | |
var storage = window.localStorage || {}; | |
// Maintain an in-memory cache. | |
function Cache() {} | |
// Set the prototype to storage. | |
Cache.prototype = storage; | |
// Create a new Cache. | |
var cache = new Cache(); | |
// Override sync on Collections, allowing them to cache. | |
Backbone.Collection.prototype.sync = Backbone.Model.prototype.sync = function(method, collection, options) { | |
// Get the correct URL. | |
var url = _.isFunction(collection.url) ? collection.url() : collection.url; | |
// Check for cache property and if an existing cache exists. | |
if (collection.cache === true && cache[url]) { | |
// Extract from sessionStroage and place into memory. | |
if (_.isString(cache[url])) { | |
cache[url] = JSON.parse(cache[url]); | |
} | |
// Trigger the success with the correct data. | |
options.success.apply(this, cache[url]); | |
// Emulate the jqXHR. | |
return $.Deferred().resolve(); | |
} | |
// Call out to default implementation. | |
var jqXHR = Backbone.sync.apply(this, arguments); | |
// Wait until complete and if successful, cache! | |
jqXHR.then(function() { | |
cache[url] = _.toArray(arguments); | |
storage[url] = JSON.stringify([arguments[0], "success", {}]); | |
}); | |
// Emulate normal Sync. | |
return jqXHR; | |
}; | |
})(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Next steps: