Skip to content

Connecting Backbone to XML Services in CoffeeScript

2012 January 24
by Nayan Hajratwala

Jeremy Anderson and I just spent several hours trying to integrate Backbone with a set of XML RESTful services. Backbone comes with built in support for JSON services, but none for XML.

We started by trying to follow this article about using Jath . It seemed promising, but had some holes. Most notable, we were hesitant to make modifications to the core backbone.js. Doing this would have prevented us from easily upgrading to new versions, etc.

The other (slightly) complicating factor was that we were using CoffeeScript and all the example code was in JavaScript.

The current release version of Backbone (0.5.3) does not allow for easily adding the options we needed to the ajax request inside sync(). While perusing the Backbone source, we discovered the the current master version on GitHub had some enhancements that made our lives easier. Downloading the master version, we were now able to pass the new parameters in the options hash.

# Keep track of the original sync method so we can
# delegate to it at the end of our new sync.
originalSync = Backbone.sync
# Our new overriding sync with dataType and ContentType
# that override the default JSON configurations.
Backbone.sync = (method, model, options) ->
options = _.extend(options,
dataType: 'xml'
contentType: 'application/xml'
processData: false
originalSync.apply(Backbone, [ method, model, options ])

Be sure not to override the incoming options with a new hash. You must simply append (extend) to the incoming options.

The last step is to get the incoming XML converted to JSON so the rest of Backbone can understand it. Below is an example using Jath as described in the above link.

class OE.Offer extends Backbone.Model
class OE.Offers extends Backbone.Collection
model: OE.Offer
url: 'http://localhost:7000/offer/opportunities/merchant/123'
parse: (response) ->
template = ["//offer", {
id: 'id',
name: 'name',
code: 'code'
Jath.parse(template, response)

Comments are closed.