Skip to main content

Backbone.js - Parsing the response from the server

From past few weeks, I've been learning Backbone.js in great detail and I think it's a great framework that helps you modularize your code easily. Last week I wrote about 'Model validation in constructor' and then started to look at Collections in Backbone. The Model objects can be viewed as table rows and the Collection as a table. A Collection can declare the model property and indicate what kind of data it will hold. I was looking into ways in which a Collection can be populated by fetching the model data from the server. One way to do that is to ask the Model to fetch the data and then add the response to the Collection. The other way of doing this is to fetch the Collection data directly from the server i.e. instead of defining a Model you create a Collection by fetching the data from the server. Usually when you send a request to the server, the response data is essentially a collection of objects. In this case you really don't need a Model to be defined.

In the Collection you can define the 'url' property and specify the URL from which the data has to be retrieved. Once the URL has been defined and an instance of Collection has been created you can call fetch on the instance to send a request to the server. Fetch will send a GET request to the server and wait for the response. While calling fetch you can specify the success and error handlers as arguments to the call:

As you can see I've defined a Collection - CarCollection and an instance of this collection - carCollectionInstance. Then I'm calling fetch on the instance, passing the success and the error callback functions. When you invoke fetch on a collection instance it would send a Ajax request to the server using jQuery's $.ajax(). Therefore it is important for you to include jQuery in the page. The URL that I've specified is a URL referring a REST resource on my ColdFusion server. This REST resource fetches some records from the database and returns the Query data in JSON format:

{"COLUMNS":["BRAND","MODEL","COLOR"],"DATA":[["Ford","Figo","RED"],["Ford","Fiesta","BLACK"],["Honda","CRV","GREEN"],["Honda","CITY","WHITE"]]}

P.S. I'm not including the code for the ColdFusion REST resource that fetches the records from the database. This is beyond the scope of this post, however you can refer to the series of posts that I've written on RESTful WebServices in ColdFusion here - http://www.sagarganatra.com/search/label/REST

The JSON response contains two keys 'COLUMNS' and 'DATA', but essentially it is one JSON object. Since the collection is modified the reset event bound to the collection would be called first and then the success handler:
Inside event d {length: 1, models: Array[1], _byId: Object, _byCid: Object, _callbacks: Object} Inside success d {length: 1, models: Array[1], _byId: Object, _byCid: Object, _callbacks: Object}

You can see that there is only one model object added to the Collection. The Model objection contains the keys 'COLUMN' and 'DATA'. This is not the format in which I wanted my collection to look like. I wanted a collection that looked like this:
{BRAND: "Ford", MODEL: "Figo", COLOR: "RED"} {BRAND: "Honda", MODEL: "CRV", COLOR: "GREEN"} ....

After reading Backbone documentation, I came across the property called parse that can be defined in the Collection. When parse is defined, the response of the fetch is first given to this function and then the reset and success event handlers are invoked. In parse you can modify the collection as per your need and it is very important to return the data from this function:


The return statement in the parse function is very important, because if it's not present then it would result in an empty collection. Now when I log the output, I can see that the collection contains Models in the desired format. Also, you would see that there are four models in collection in both reset and success event handlers.

Comments

Popular posts from this blog

Adding beforeRender and afterRender functions to a Backbone View

I was working on a Backbone application that updated the DOM when a response was received from the server. In a Backbone View, the initialize method would perform some operations and then call the render method to update the view. This worked fine, however there was scenario where in I wanted to perform some tasks before and after rendering the view. This can be considered as firing an event before and after the function had completed its execution. I found a very simple way to do this with Underscore's wrap method.

De-obfuscating javascript code in Chrome Developer Tools

I had blogged about JavaScript debugging with Chrome Developer Tools  some time back, wherein I have explained how these developer tools can help in debugging javascript code. Today Google Chrome 12 was released and my Chrome browser was updated to this version. As with every release, there have been some improvements made on performance, usability etc,. One feature that stood out for me is the ability to De-obfuscate the javascript code. What is Minification? Minification is the process of removing unnecessary characters such as white spaces, comments, new lines from the source code. These otherwise would be added to make the code more readable. Minifying the source code helps in reducing the file size and thereby reducing the time taken to download the file. This is the reason why most of the popular javascript libraries such as jQuery are minified. A minified jQuery file is of 31 KB in size where as an uncompressed one is about 229 KB. Unfortunately, debugging minified javascript f

On GraphQL and building an application using React Apollo

When I visualize building an application, I would think of using React and Redux on the front-end which talks to a set of RESTful services built with Node and Hapi (or Express). However, over a period of time, I've realized that this approach does not scale well when you add new features to the front-end. For example, consider a page that displays user information along with courses that a user has enrolled in. At a later point, you decide to add a section that displays popular book titles that one can view and purchase. If every entity is considered as a microservice then to get data from three different microservices would require three http  requests to be sent by the front-end app. The performance of the app would degrade with the increase in the number of http requests. I read about GraphQL and knew that it is an ideal way of building an app and I need not look forward to anything else. The GraphQL layer can be viewed as a facade which sits on top of your RESTful services o