Created
April 12, 2012 21:01
-
-
Save jgibbon/2370971 to your computer and use it in GitHub Desktop.
Mootools Cached Request with localStorage
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
/* | |
--- | |
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