Skip to content

Instantly share code, notes, and snippets.

@boazsender
Forked from tbranyen/backbone.collectioncache.js
Created August 30, 2012 16:46
Show Gist options
  • Save boazsender/3532848 to your computer and use it in GitHub Desktop.
Save boazsender/3532848 to your computer and use it in GitHub Desktop.
Backbone.Collection caching by URL
/*!
* 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);
@boazsender
Copy link
Author

Next steps:

  • Make serialization more intelligently be able to walk down the attributes property of a model, looking for collections.
  • Support session and local storage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment