Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple request mixin for Flight
/*
this.ajax({
xhr: {
url: 'some/thing'
},
events: {
done: 'somethingDone',
fail: { node: document, event: 'ajaxError' }
}
})
*/
define(function(require) {
function withRequests() {
this.get = function(options) {
return this.ajax(options, 'get');
};
this.post = function(options) {
return this.ajax(options, 'post');
};
this.ajax = function(options, type) {
var xhr = _.extend(options.xhr, {
context: this,
type: type,
dataType: 'json'
}),
events = options.events;
if (typeof events.before === 'string') {
this.trigger(events.before);
delete events.before;
}
var req = $.ajax(xhr);
_.each(events, function(value, key) {
req[key](function () {
var args = [].slice.call(arguments, 0);
if (typeof value === 'string') {
this.trigger(value, args);
} else if (typeof value === 'object') {
this.trigger(value.node, value.event, args);
}
});
});
return req;
};
}
return withRequests;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment