-
-
Save ryun/4350428 to your computer and use it in GitHub Desktop.
Ajax auto-cache
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
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 | |
}); | |
}) |
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
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