cached jsonp twitter
by Dimitar Christoff
HTML
<div id="userData"></div>
JavaScript
Request.JSONP.implement(new new Class({
storage: {},
storageMethod: "sessionStorage",
setupStorage: function() {
// window[this.storageMethod].clear();
this.hasNativeStorage = !!(typeOf(window[this.storageMethod]) == "object" && window[this.storageMethod].getItem);
if (this.hasNativeStorage) this.storage = JSON.decode(window[this.storageMethod].getItem("myStorage")) || this.storage;
},
getItem: function(item) {
return this.storage[item] || null;
},
setItem: function(item, value) {
console.info(item, value, typeOf(value));
this.storage[item] = value;
if (this.hasNativeStorage) {
try {
window[this.storageMethod].setItem("myStorage", JSON.encode(this.storage));
}
catch (e) {
// security error.
}
}
}
}));
Request.twitterUSER = new Class({
Extends: Request.JSONP,
options: {
userObj: "userData",
url: "http://api.twitter.com/1/users/show/{user}.json"
},
initialize: function(user, options) {
this.user = user;
this.setupStorage();
this.parent(options);
this.options.url = this.options.url.substitute({user: user});
},
send: function(options) {
if (this.getItem(this.user)) {
console.info("loaded from cache: ", this.getItem(this.user));
this.success([this.getItem(this.user)]);
return;
}
this.parent(options);
},
success: function(args) {
this.setItem(this.user, Array.prototype.slice.call(args)[0]);
this.parent(args);
}
});
new Request.twitterUSER("D_mitar", {
onComplete: function(data) {
console.log(data);
}
}).send();
(function() {
new Request.twitterUSER("D_mitar", {
onComplete: function(data) {
console.log(data);
}
}).send();
}).delay(4000);