Backbone.js struggles with rendering collection object fields when the JSON response is enclosed within a "book" domain wrapper

Upon receiving the following JSON data, the view and HTML code successfully renders the values on the webpage.

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 the above Template

 <% _.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 attempted various methods to achieve the same result with the following JSON response but encountered failures. Can someone provide guidance on what logic adjustments should be made if the JSON DATA is in the following format

{"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"}]}

Answer β„–1

When using Backbone collections, it is important to note that by default they expect an array in the response of a .fetch call. If you need to change this to a JSON structure, you will have to parse the data first. One way to do this is by overriding the parse function for your collection. Check out for more information.

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

Feel free to add any additional error handling or parsing inside the parse function as needed. Just make sure the response type remains as the array of Book JSON objects.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a @HostListener that is activated only when the component is invoked

Using an Angular application with a ngx-datatable that autogenerates rows. Each row contains an action that triggers a popup of items, which is a separate component from the table. The popup is called from the table using a parent-child link as shown below ...

When attempting to browse for image files, Postman fails to display images

While trying to upload image files through Postman, I encountered an issue where the browser did not display any image files. It's important to note that I am using Ubuntu as my operating system. https://i.sstatic.net/1D3ro.png When I clicked on "se ...

Ways to conceal the unchecked checkbox's parent element?

I am working with a series of dynamically generated div checkboxes: <div>X1 <input type='checkbox' name='X[]' value='X1'> </div> <div>X2 <input type='checkbox' name='X[]' value=& ...

"Despite receiving a successful response from curl, AWS Lambda and API Gateway return a 500 error when accessed from a

I am facing challenges with AWS Lambda and API Gateway. While I can successfully call my API using curl and Postman, I am unable to do so from my browser. It works when: curl --header "Content-Type: application/json" \ --request POST \ ...

Having trouble setting up Node.js on a Mac computer

Upon completing the regular installation on Mac, I am unable to find Node in the terminal. Even after defining the PATH with the line: export PATH=/usr/local/bin: $PATH, it still does not locate Node or npm in the terminal. ...

Exploring different paths using React Links

<Router> <Homepage /> </Router> Given that the Homepage component displays a menu of links and routes, will clicking on a link cause the entire component to refresh? ...

Determining the number of items in an array using Javascript

I am working with an array that is made up of an unlimited number of objects, all with the same structure. When I log the entire array, it shows up like this: [object], [object], [object], and so on... Adding a new object to the array means I could eithe ...

Assign a value of zero to the currentItem variable upon changing to a different category

Currently, I am developing a news application that utilizes a card-based layout for scrolling through news items. In the implementation, there is a variable called currentItem that keeps track of the current index being viewed. A recurring issue arises w ...

Utilizing a search bar with the option to narrow down results by category

I want to develop a search page where users can enter a keyword and get a list of results, along with the option to filter by category if necessary. I have managed to make both the input field and radio buttons work separately, but not together. So, when s ...

What is the process for swapping true and false values ​​in HTML from JSON with online and offline statuses?

I am using a WordPress site and looking to utilize the API through JSON. The API provides a true/false result, displaying as either true or false. How can I showcase this information on the webpage as online when the result is true and offline when the res ...

Exploring and deciphering the intricacies of the underlying technology

Apologies if this question seems misplaced, but as a complete beginner, I'm a bit lost. Let's consider this website as an example: I'm trying to uncover the libraries and technologies employed in the background to learn more and replicate ...

Flask encountering an unexpected error while sending an ajax request, despite the fact that a duplicate request from another function is functioning properly

As a novice in Python and Flask, I have found it incredibly helpful to use them for running a webapp on my Raspberry Pi. Initially, I developed the app in HTML with JavaScript handling the logic. Now that I have a "finished" app, I am looking to enhance i ...

Tips for customizing the main select all checkbox in Material-UI React data grid

Utilizing a data grid with multiple selection in Material UI React, I have styled the headings with a dark background color and light text color. To maintain consistency, I also want to apply the same styling to the select all checkbox at the top. Althou ...

Tips for ensuring a button functions for only the specific element clicked, not all elements in a rendered list

I have a list that was generated from an array, with each element having a menu button that opens a modal specific to that element. However, I am facing an issue where clicking on the button for one index triggers the modal for all indexes instead of just ...

Ways to shift placeholder text slightly to the right within a select dropdown?

Struggling with this issue for hours, I can't seem to figure out how to: Adjust the position of the placeholder text (Search) by 10 pixels to the right in my select component Reduce the height of the field (maybe by 5px) without success. Could someo ...

How can a controller be used to access and modify data from various partials?

I need assistance with handling multiple ng-models spread across 2 partial HTML files. Here is the content of partial1.html: <input ng-model="A" /> //user input for A <input ng-model="B" /> //user input for B <input ng-model="C" /> //us ...

Using Bootstrap 4 to Filter Cards by Title and Tag

I'm attempting to develop searchable cards using HTML, JavaScript, and Bootstrap 4, but I'm facing issues with my code. My goal is to filter these three cards using a search bar, based on their title (h5.card-title) and tags (a.badge). Below is ...

What is the best way to map elements when passing props as well?

In my code, I am using multiple text fields and I want to simplify the process by mapping them instead of duplicating the code. The challenge I'm facing is that these textfields also require elements from the constructor props. import React, { Compon ...

Using Javascript to iterate over an array

Issue: I am facing a challenge with updating an array containing image links. The goal is to add new image links while retaining previously uploaded images in the array. However, the problem arises when the previous image links are getting combined. See ex ...

Swapping text occurrences individually with JavaScript

Seeking a way to dynamically replace multiple placeholder texts through JavaScript. Attempted using jquery filter and contain selector without much success. Any suggestions on how to achieve this? <div class="container"> <h1>$$Insert text here ...