Skip to content

Instantly share code, notes, and snippets.

@simonsmith
Last active May 22, 2016 09:51
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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);
});
}
});
}
};
@dannymidnight
Copy link

I wrote something very similar that can also trigger events on other DOM elements ie. document.

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() {
      var args = [].slice.call(arguments);
      var event = args.shift();

      if (typeof event === 'string') {
        this.trigger(event, args);
      } else if (typeof event === 'object') {
        this.trigger(event.node, event.event, args);
      }
    }, this, events[e]));
  }

  return req;
};

eg.

this.ajax({
  xhr: {
    url: 'some/thing'
  },
  events: {
    done: 'somethingDone',
    fail: { node: document, event: 'ajaxError' }
  }
})

@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