Last active
May 22, 2016 09:51
-
-
Save simonsmith/5089415 to your computer and use it in GitHub Desktop.
Ajax mixin for Flight - https://github.com/twitter/flight
This file contains 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
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); | |
}); | |
} | |
}); | |
} | |
}; |
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
I wrote something very similar that can also trigger events on other DOM elements ie.
document
.eg.