Search code examples
javascriptjsonbackbone.js

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.

JSON DATA

[{"id":"1234","name":"book1","type":"catg1"},{"id":"1235","name":"book2","type":"catg1"},
        {"id":"1236","name":"book3","type":"catg1"},
        {"id":"1237","name":"book4","type":"catg1"},
        {"id":"1238","name":"book5","type":"catg1"}]

Collection and Model

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

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

VIEW

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

HTML rendered using above Templet

 <% _.each(books, function(book) { %>
          <tr>
            <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

    {"book":[{"id":"1234","name":"book1","type":"catg1"},
{"id":"1235","name":"book2","type":"catg1"},
    {"id":"1236","name":"book3","type":"catg1"},
    {"id":"1237","name":"book4","type":"catg1"},
    {"id":"1238","name":"book5","type":"catg1"}]}

Solution

  • 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 http://backbonejs.org/#Collection-parse for more info.

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

    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.