Skip to content

Instantly share code, notes, and snippets.

@simonsmith
Last active May 22, 2016 09:51
Show Gist options
  • Save simonsmith/5089415 to your computer and use it in GitHub Desktop.
Save simonsmith/5089415 to your computer and use it in GitHub Desktop.
Ajax mixin for Flight - https://github.com/twitter/flight
module.exports = withAjax;
function withAjax() {
'use strict';
this.get = function(url, options) {
this.ajax(url, options, 'get');
};
this.post = function(url, options) {
this.ajax(url, options, 'post');
};
this.ajax = function(url, options, type) {
var xhr = $.extend(options.xhr, {
context: this,
type: type,
dataType: 'json'
});
var events = options.events;
var meta = (typeof options.meta === 'object' ? options.meta : {});
if (typeof events.before === 'string') {
this.trigger(events.before);
delete events.before;
}
var req = $.ajax(url, xhr);
$.each(events, function(key, value) {
if (typeof value === 'string') {
req[key](function() {
// Push meta data in as second member for cleaner
// callback params
var args = [].slice.call(arguments, 0);
args.splice(1, 0, meta);
this.trigger(value, args);
});
}
});
}
};
@simonsmith
Copy link
Author

Ah nice, this seems much more succinct. Fixed mine up a little to.

Cheers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment