Skip to content

Instantly share code, notes, and snippets.

@dannymidnight
Created March 29, 2014 16:37

Revisions

  1. dannymidnight created this gist Mar 29, 2014.
    117 changes: 117 additions & 0 deletions with_ajax.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,117 @@
    "use strict";

    //
    // This mixin triggers flight events on xhr requests
    // by wrapping appropriate jquery xhr callbacks.
    //
    // eg.
    // this.ajax({
    // xhr: {
    // url: '/do/something',
    // data: {}
    // },
    // events: {
    // done: 'somethingDone',
    // fail: { node: document, event: 'somethingFail' }
    // }
    // });
    //

    define(

    [
    'flight/lib/utils'
    ],

    function(utils) {

    function withAjax() {

    //
    // Get options from arguments with [url] as either
    // a string or attribute of [options] object.
    //
    // @returns object
    //
    var getOptions = function(args) {
    var url, options;
    args = utils.toArray(args);

    if (typeof(args[0]) === 'string') {
    url = args.shift();
    options = args[0];
    } else {
    options = args[0];
    url = options.xhr.url;
    }

    return $.extend(true, {
    xhr: {
    url: url
    }
    }, options);
    };

    //
    // Usage: this.post([url], options)
    //
    this.post = function() {
    var options = getOptions(arguments);

    return this.ajax($.extend(true, {
    xhr: {
    type: 'post'
    }
    }, options));
    };

    //
    // Usage: this.get([url], options)
    //
    this.get = function() {
    var options = getOptions(arguments);

    return this.ajax($.extend(true, {
    xhr: {
    type: 'get'
    }
    }, options));
    };

    //
    // Usage: this.getJSON([url], options)
    //
    this.getJSON = function() {
    var options = getOptions(arguments);

    return this.ajax($.extend(true, {
    xhr: {
    type: 'get',
    dataType: 'json'
    }
    }, options));
    };

    this.ajax = function(options) {
    var events = options.events;
    var xhr = $.extend(options.xhr, {
    context: this
    });

    var req = $.ajax(xhr);
    for (var e in events) {
    req[e]($.proxy(function(event, res) {
    if (typeof event === 'string') {
    this.trigger(event, [res]);
    } else if (typeof event === 'object') {
    this.trigger(event.node, event.event, res);
    }
    }, this, events[e]));
    }
    return req;
    };
    }

    return withAjax;
    }
    );