Skip to content

Instantly share code, notes, and snippets.

@subchild
Created October 13, 2010 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save subchild/624135 to your computer and use it in GitHub Desktop.
Save subchild/624135 to your computer and use it in GitHub Desktop.
Loader
/**
* Loader instances support evented ajax calls, with caching
* @requires $.bindable()
*/
var Loader = function(){
this._cache = {};
};
Loader.prototype.load = function(cfg){
var _self = this,
_cfg = {},
_cacheKey = cfg.url+"?"+$.param(cfg.data);
if (_self._cache[_cacheKey]){
// return cached data
_self.trigger("load.success", [_self._cache[_cacheKey]]);
return;
}
// defaut config
_cfg = {
url : "",
type : "GET",
dataType : "json",
data : {},
success : function(data){
_self.trigger("load.success", [data]);
_self._cache[_cacheKey] = data;
},
error : function(){
_self.trigger("load.error");
}
};
// extend with passed config
_cfg = $.extend(true, _cfg, cfg);
$.ajax(_cfg);
}
$.bindable(Loader);
// example:
var someLoader = new Loader();
someLoader
.bind("load.success", function(e, data){
// do stuff with data
})
.load({
url : "http://someurl.com/someEndpoint",
data : {a:0, b:1}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment