yeppe yeppe - 2 years ago 71
Javascript Question

backbonejs- not able to render the fields of collection object when json response is wrapped with domain book

When below json data is received the view and html code renders the values correctly in the html page.



Collection and Model

var books= Backbone.Collection.extend({
url: '/books'

var Book= Backbone.Model.extend({
urlRoot: '/books'


var bookListView = Backbone.View.extend({
el: '.page',
render: function () {
var that = this;
var books= new Books();
success: function (banks) {
var template = _.template($('#book-list-template').html(), {books: books.models});

HTML rendered using above Templet

<% _.each(books, function(book) { %>
<td><%= htmlEncode(book.get('id')) %></td>
<td><%= htmlEncode(book.get('name')) %></td>
<td><%= htmlEncode(book.get('type')) %></td>

<% }); %>

However, I tried various approaches to do the similar thing with the below Json response but failed. Can anyone explain what should I alter in the logic if the Json DATA comes as below


Answer Source

Backbone collections by default assume an array in the response of a .fetch call. So changing it to a JSON structure means you need to parse the data first. Overriding the parse function for your collection should solve your problems. See for more info.

var Book = Backbone.Model.extend({});
var books= Backbone.Collection.extend({
  url: '/books',
  model: Book,
  parse: function(data) {

You can add any additional error/parsing that you see fit inside of that parse function. The response type should be the array of Book JSON.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download