Consuming XML with Backbone.js

Posted by

http://www.flickr.com/photos/geraldpereira/6140017255/sizes/l/in/photostream/

Like many HTML 5 oriented frameworks, JSON is the way to do things and Backbone.js is no exception. So what do we do when data coming from the server is XML?  We can still use Backbone. Since Backbone.js is using jQuery under the hood, the capability should be there.

We know that the Collection object in Backbone is where all things related to data happen, so that should be a good place to start. The first problem is that the Collection.fetch method does not expect XML from the server. By reading the Backbone documentation we can see that the fetch method in Collection takes an options hash argument. This is the settings object that configures the underlying jQuery Ajax request .
With the settings object, we can configure the fetch method to tell jQuery that we are expecting XML from the server by setting the dataType to XML.

Now that the the XML is flowing in, we need to parse it to our app's model objects. Again, by consulting the documentation we'll find that the Collection.parse function can do this. The parse function is called by Backbone whenever a collection's models are returned by the server, in fetch, and by using jQuery we can query the XML and create model objects.

Which should return an array of model objects

And that's it. This is one way to make XML work with Backbone.js by telling the jQuery Ajax request to expect an XML response and parse the XML to Backbone models without any kludges.
Please feel free to use the comment section if there are other ways to do this.

Happy coding!

Comments