Skip to content

Instantly share code, notes, and snippets.

@kamikat
Created March 30, 2014 15:12
Show Gist options
  • Save kamikat/9874209 to your computer and use it in GitHub Desktop.
Save kamikat/9874209 to your computer and use it in GitHub Desktop.
AJAX wrapper to jQuery's AJAX API to achieve a more scientific response handle framework
// @require `underscore` or `lodash`
// Figure out type of `obj'
var typeid = function (obj) {
return Object.prototype.toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
};
var ajax = function (method, url, data, options, handler) {
if (typeid(options == 'function')) {
handler = options; options = {};
}
_(options).extend({
method: method,
url: url,
data: data,
complete: function (xhr, statusText) {
if (typeid(handler) == 'function') {
return handler(xhr.responseJSON || xhr.responseXML || xhr.responseText, xhr.status, xhr);
}
}
});
return $.ajax(options);
};
_(ajax).extend({
///
// ajax.handler([Object]);
// ajax.handler([Array]);
// ajax.handler([String status | Array], [Function handler | Array]);
// ajax.handler([Function matcher], [Function handler | Array]);
///
handler: function (matcher, handler, _collection) {
if (!handler) {
handler = matcher;
if (typeid(handler) == 'object') {
handler = _.map(handler, function (handler, matcher, _collection) {
return ajax.handler(matcher, handler, _collection);
});
}
if (typeid(handler) == 'array') {
return function (data, status, xhr) {
_.each(handler, function (handler) { handler(data, status, xhr); });
};
}
} else {
if (matcher == '*') {
matcher = function () { return true; };
}
if (matcher == '___') {
matcher = function (data, status, xhr) {
return !~Object.keys(_collection).indexOf('' + status);
};
}
if (typeid(matcher) == 'string') {
matcher = [ matcher ];
}
if (typeid(matcher) == 'array') {
matcher = function (matcher) {
return function (data, status, xhr) {
return !!~matcher.indexOf('' + status);
};
}(matcher);
}
if (typeid(handler) == 'array') {
handler = function (handler) {
return function (data, status, xhr) {
_.each(handler, function (handler) { handler(data, status, xhr); });
};
}(handler);
}
if (typeid(matcher) == 'function') {
return function (data, status, xhr) {
return matcher(data, status, xhr) && handler(data, status, xhr);
};
}
}
}
});
_.each(['post', 'get'], function (method) {
ajax[method] = ajax.bind(null, method);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment