Backbone.js - Parsing the Response from the Server
Join the DZone community and get the full member experience.
Join For FreeIn 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:
var CarCollection = Backbone.Collection.extend({
//Specify REST URL
url: 'http://localhost:8500/rest/Car/CarService',
initialize: function () {
this.bind("reset", function (model, options) {
console.log("Inside event");
console.log(model);
});
}
});
var carCollectionInstance = new CarCollection();
carCollectionInstance.fetch({
success: function(response,xhr) {
console.log("Inside success");
console.log(response);
},
error: function (errorResponse) {
console.log(errorResponse)
}
});
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:
(function () {
//Create a Car Collection
var CarCollection = Backbone.Collection.extend({
//Specify REST URL
url: 'http://localhost:8500/rest/Car/CarService',
//Parse the response
parse: function (response) {
console.log("Inside Parse");
//keys
var keys = response.COLUMNS;
//values
var values = response.DATA;
//Parse the response and construct models
for (var i = 0, length = values.length; i < length; i++) {
var currentValues = values[i];
var carObject = {};
for (var j = 0, valuesLength = currentValues.length; j < valuesLength; j++) {
carObject[keys[j]] = currentValues[j];
}
//push the model object
this.push(carObject);
}
console.log(this.toJSON());
//return models
return this.models;
},
initialize: function () {
this.bind("reset", function (model, options) {
console.log("Inside event");
console.log(model);
});
}
});
var carCollectionInstance = new CarCollection();
carCollectionInstance.fetch({
success: function(response,xhr) {
console.log("Inside success");
console.log(response);
},
error: function (errorResponse) {
console.log(errorResponse)
}
});
})();
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.
Published at DZone with permission of Sagar Ganatra, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments