Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.