Skip to content

Instantly share code, notes, and snippets.

@gka
Created January 12, 2012 21:57
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 gka/1603394 to your computer and use it in GitHub Desktop.
Save gka/1603394 to your computer and use it in GitHub Desktop.
Ender extension for firing multiple ajax requests at once

Makes loading of multiple assets easier

Usage:

$.loadAssets({
	assets: {
		'asset1': 'foo.html',
		'asset2': { url: 'bar.json', type: 'jsonp' }
	},
	success: function(data) {
		// do something with data.asset1 and data.asset2
	}
});
Function::bind ?= (scope) ->
_function = this
() ->
_function.apply scope, arguments
$.ender
loadAssets: (opt) ->
data = {}
cnt = 0
for id of opt.assets
asset = opt.assets[id]
if typeof(asset) == "string"
opt.assets[id] = { url: asset, type: 'text' }
cnt++
context =
id: id
loaded = (content) ->
data[this.id] = content
for id2 of opt.assets
if not data[id2]? then return
opt.success data
$.ajax
url: asset.url
method: asset.method
type: asset.type
data: asset.data
success: loaded.bind context
error: (a) ->
console.error a
if cnt == 0 then opt.success data
if ((_ref = (_base = Function.prototype).bind) == null) {
_base.bind = function(scope) {
var _function;
_function = this;
return function() {
return _function.apply(scope, arguments);
};
};
}
$.ender({
loadAssets: function(opt) {
var asset, cnt, context, data, id, loaded;
data = {};
cnt = 0;
for (id in opt.assets) {
asset = opt.assets[id];
if (typeof asset === "string") {
opt.assets[id] = {
url: asset,
type: 'text'
};
}
cnt++;
context = {
id: id
};
loaded = function(content) {
var id2;
data[this.id] = content;
for (id2 in opt.assets) {
if (!(data[id2] != null)) return;
}
return opt.success(data);
};
$.ajax({
url: asset.url,
method: asset.method,
type: asset.type,
data: asset.data,
success: loaded.bind(context),
error: function(a) {
return console.error(a);
}
});
}
if (cnt === 0) return opt.success(data);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment