Exploring an array of JSON data with HandlebarsJS and BackboneJS

My goal is to showcase a collection of music artists organized by the first letter of their name.

This is how I have set up my Backbone View:

function (App, Backbone, utils) {

    // Define a new module.
    var AllArtists = App.module();

    // Create view
    AllArtists.View = Backbone.View.extend({
        template: 'allArtistsList',
        initialize: function() {
            //this.listenTo(this.collection, 'sync', this);
        },
        afterRender: function(){
            var col1 = new Backbone.Collection();
            col1.url = App.APIO + '/i/search/artist?name=a';
            col1.fetch({success: function(){
                console.log(col1);
            }});
            this.insertView('.artistsA', new AllArtists.View({collection: col1}));

            var col2 = new Backbone.Collection();
            col2.url = App.APIO + '/i/search/artist?name=b';
            col2.fetch({success: function(){
                console.log(col2);
            }});
            this.insertView('.artistsB', new AllArtists.View({collection: col2}));          
        }
    });

    return AllArtists;
}

Next, let's take a look at my Handlebars HTML:

<div class="artistsA">
    {{#each this}}
        <a href="{{name}}">{{name}}</a>
    {{/each}}   
</div>

Currently, the JSON data structure resembles the following (for the letter 'a' in this case):

data: [ 
        {
           artist_id:78, 
           name:A Band Of Boys
         },
          {
           artist_id:79, 
           name:a Beautiful Friend
         },
         {
           artist_id:80, 
           name:A Camp
        } 
        and so forth...

While I can see the data being logged in the console, the webpage appears blank. It seems like there might be an issue with my implementation of Handlebars. Any insights on what could be going wrong?

Answer №1

When using fetch(), it operates asynchronously by internally initiating an Ajax request, which is also asynchronous in nature. To ensure that the insertView() function is called only after a successful fetch operation, you must place this call within the success callback. Otherwise, attempting to execute insertView() before receiving any data will result in a blank page being displayed.

If there is a need to transform the request into a synchronous one, you can achieve this by including the property {async:false}

col1.fetch({async:false});

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

Trigger file download with ajax and php

I have been using an image picker plugin to select an image and then force it to download. Initially, I hard coded the PHP which worked perfectly fine. The download pop-up appeared and I was able to view the file without any issues. However, when trying to ...

What is the purpose of sorting an object using the sequence defined in an array?

Have you ever wondered how the sortWeekFunction function can rearrange an object based on a predefined array order? It may seem complex at first glance, but let's break down how this code actually works. const weeksArr = ['sunday', ' ...

Vue: Develop a master component capable of displaying a sub-component

Is there a way to design a main component that is able to accept and display a subcomponent? Take the following scenario for instance: <Container> <Item/> <Item/> <SubMenu/> <Btn/> </Container> ...

When utilizing a third-party library in conjunction with Vuetify, the V-menu may have a tendency to automatically close right after

Incorporating cytoscape into a vuetify SPA has been successful for the most part. The graph renders within a v-card-element, and I can navigate to a different page using the vue router when clicking a note in the graph. However, when attempting to replace ...

Problem with unusual symbols

I am experiencing a problem where special characters are not displaying correctly on my website. To address this, I am executing an ajax query with a Python script on the backend : $.ajax({ ...

Tips on obtaining the response (in JSON format) in your console when accessing a URL

Can someone help me integrate this code into my project and guide me on how to proceed with it? function validate() { var un = document.loginscreen.uname.value; var pw = document.loginscreen.psw.value; var username = "John_Smith"; var passw ...

Encountering Problem with Jmeter Script Playback - Kindly Activate JavaScript to Access Page Information

I'm currently experiencing a challenge when trying to simulate the following scenario in my JMeter script. I would truly appreciate any assistance or solutions you can offer. My goal is to create a JMeter script for a form submission process within a ...

Sending data from client to Node.js with strings

Over the past few days, I've been on a relentless quest to figure out how to transfer a string from the client side to Node.js, but unfortunately, my efforts have been in vain. Currently, I am grappling with a form containing numerous inputs and an i ...

Preserve the output from the jQuery ajax request

I have created a custom function that calls an ajax request and saves the response data to a variable before returning it. It always shows '0' as the return value, but the alert displays numbers like 3712. Below is the implementation of the func ...

In the event that the get request fails, go ahead and clear the

Currently facing an issue and seeking a solution: I have a game running that retrieves the state of the game periodically. However, if a user logs out, the game ends but continues to send put requests at the set interval. I am exploring options like setti ...

Optimizing jqGrid: Enhancing saveRow function to properly synchronize with editRow function

Exploring how to customize jqGrid's add function for my own needs. I have a navButton with specific requirements: When the user clicks the button, a new row in edit mode should appear on the grid. Once the user enters data and presses enter, the dat ...

The custom tab component in React is currently not accepting the "disabledTabs" prop

I have designed a tab component as shown below: tab/index.jsx import React from 'react'; import TabHeader from './header'; import TabBody from './body'; import TabHeaderList from './header/list'; import TabBodyList ...

What is the best way to determine in component.html whether the column type is equal to 1 to show the label text "Active,"

Having trouble checking the value of an object named ReportControl. If the column type is 1, display the label "active"; otherwise, display the label "not active" on reportcomponent.html. The data for the ReportControl object is as follows: {"reportId": ...

Why does the removeChild method in JavaScript consistently remove the last child element, rather than the one specified by its ID?

There are four divs with an event listener onclick, triggering a JavaScript function that simply removes the clicked div: this.parentNode.removeChild(this); Although it should remove the specific div clicked on, it instead deletes the last child and alte ...

Utilizing the power of jQuery's $.each method to dynamically generate HTML select options within an AJAX

I am working with a bootstrap modal that includes a form which requires data from the database. To retrieve this data, I am using PHP as shown below: public function get_view_for_inspection_report_belum_eor(){ $q = $this->inspection->get_view_fo ...

Looking to optimize this code? I have three specific tags that require reselection within a given list

for (var i=0; i<vm.tags.length; i++) { if (selectedTags[0]) { if (vm.tags[i].term_id === selectedTags[0].term_id) { vm.tags[i].border1 = true; } } if (selectedTags[1]) { if (vm.tags[i].term_id === selecte ...

`problem with moment.js incorrectly identifying the day of a given date`

I'm currently working with a field that has the value 03-01-2020, which is in the DD-MM-YYYY date format. However, when I apply the code moment.utc(document.getElementById('date').value, "DD-MM-YYYY HH:mm:ss").toDate(), I noticed that the re ...

Exploring the use of the Next.js page router for implementing internationalization (i18

I need assistance implementing Dutch and English language translations for my entire website. Can anyone provide guidance? I have tried using i18n localizely, but it only works for individual pages. I am looking to implement translations on a larger scale ...

Using JSON in JavaScript to handle the click event of ASP.NET buttons

Here is the code that works well for me. I need to execute two different server-side functions, and they can't run at the same time as I have separated them. Default.aspx/AddCart btnUpdate Click Event The issue I'm facing is that the alert box ...

Retrieving data from a JSON file at 10-minute intervals with Ajax and visualizing it on Google's globe API

After downloading Armsglobe, a globe API provided by Google to draw lines in countries using their names, I noticed that the original code does not fetch JSON data periodically. I attempted to use a simple setTimeout() function in dataloading.js to address ...