Backbone CrossDomain Library

Open sourcing the Backbone.CrossDomain Library

The Problem: Microsoft and their own Cross Domain Request object

I recently came across a situation at work where I needed to do a cross domain POST on IE. We have these complex forms loaded entirely in client-side js using Backbone which we want loadable on any page but which need to submit their data directly to our API servers using CORS.

This turned out to be a non-trivial problem.

See it turns out that instead of using the XMLHttpRequest object used by jQuery or Zepto’s $.ajax(), when doing a cross domain request (such as a POST from a site served off of https://foo.com to the endpoint https://bar.com) Microsoft decided it made sense to create an entirely different request object called XDomainRequest. More details here

#comeonmicrosoft

Practically speaking, this means that neither jQuery nor Backbone work with CORS requests out of the box on IE 7, 8, and 9. Thankfully Microsoft came to their senses in IE 10 and XMLHttpRequest works fine (and so thus do jQuery and Backbone) but for earlier versions it didn’t work and sadly my company cannot yet ignore the IE populace.

The XDomainRequest functions similarly to the XMLHttpRequest object, but just different enough to be a pain.

The Solution: I created the Backbone.CrossDomain library

Our app infrastructure is all in Backbone, so I was able to write the code to handle this once and never think about it.

In my library I simply overwrote Backbone.sync which allowed the rest of our code to stay exactly the same. Things that just threw errors before on IE now just work. Like magic.

I wrote with AMD support baked in because RequireJS rocks and I tried hard to make it a drop-in replacement for the standard Backbone.sync and it still defers to Backbone.sync on every normal modern browser, but will use this XDomainRequest object when necessary.

This project is open-source and available:

On Github at https://github.com/victorquinn/Backbone.CrossDomain

and

On npm as backbone-crossdomain

Published 11 Mar 2013

Scaling and leading engineering and data teams to solve the world's problems
Victor Quinn on Twitter