Skip to content

Instantly share code, notes, and snippets.

@jgibbon
Created April 12, 2012 21:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgibbon/2370971 to your computer and use it in GitHub Desktop.
Save jgibbon/2370971 to your computer and use it in GitHub Desktop.
Mootools Cached Request with localStorage
/*
---
name: Request.Cacheable
description: Extends the basic Request Class with lazy localStorage Cache. Tested: No. Guaranteed to work: No. Limitations: Many. The Attribute Name in the Cache Object is only the provided url. You can use another Prefix though.
license: MIT-style license.
requires: [Request]
provides: Request.Cacheable
...
*/
(function(){
'use strict';
Request.Cacheable = new Class({
Extends: Request,
options: {
storageKey: 'Request.Cacheable',
requestKeyPrefix: ''
},
initialize: function (options) {
this.parent(options);
},
send: function (options) {
var type, opt;
this.parent(options);
if (!localStorage) { return; }
type = typeOf(options);
if (type === 'string' || type === 'element') {
options = {data: options};
}
opt = this.options.requestKeyPrefix + ((options ? options.url : null) || this.options.url);
this.store = JSON.decode(localStorage.getItem(this.options.storageKey)) || {};
if (typeof this.store[opt] !== 'undefined') {
this.onSuccess.apply(this, this.store[opt]);
}
},
success: function (text, xml) {
var opt;
if (localStorage) {
opt = this.options.requestKeyPrefix + this.options.url;
this.store = JSON.decode(localStorage.getItem(this.options.storageKey)) || {};
this.store[opt] = Array.prototype.slice.call(arguments);
localStorage.setItem(this.options.storageKey, JSON.encode(this.store));
}
this.parent(text, xml);
},
deleteAll: function () {// ;)
localStorage.removeItem(this.options.storageKey);
}
});
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment