Skip to content

Instantly share code, notes, and snippets.

@ryun
Forked from anonymous/Usage.js
Last active December 10, 2015 00:19
Show Gist options
  • Save ryun/4350428 to your computer and use it in GitHub Desktop.
Save ryun/4350428 to your computer and use it in GitHub Desktop.
Ajax auto-cache
var aCache = new ajaxCache({pk: "folder_id", prefix: "folder");
$('#folder_sel').change(function() {
var folder_id = $(this).val();
aCache.post(href_val, {'folder_id': folder_id}, function(data) {
//code
});
})
var ajaxCache = function(cfg){
this._cache = {};
this._pk = cfg.pk||null;
this._prefix = cfg.prefix||'';
};
ajaxCache.prototype = {
constructor: ajaxCache,
set: function(key, val) {
this._cache[key] = val;
},
get: function(key) {
return this.exists(key) ? this._cache[key] : null;
},
exists: function(key) {
return key in this._cache;
},
fetch: function(method, url, data, callback, type) {
if ( $.isFunction( data ) )
{
type = type || callback;
callback = data;
data = undefined;
}
var self = this
key = this._pk ? this._pk+':'+data[this._pk] : url;
key = this._prefix + key;
if (this.exists(key))
{
return callback.call(this, self.get(key));
}
return $.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: function(data) {
self.set(key, data);
callback.call(this, data);
}
});
},
load: function(url, data, callback, type) {
this.fetch('get', url, data, callback, type );
},
post: function(url, data, callback, type) {
this.fetch('post', url, data, callback, type );
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment