Created
August 13, 2013 23:43
-
-
Save cam-stitt/6226780 to your computer and use it in GitHub Desktop.
A simple request mixin for Flight
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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