Trouble with Backbone: collection not rendering JSON data in the view

I'm having trouble getting the JSON data in my FriendsCollection to display in FriendListView. I can confirm that the data is being loaded through the network panel and I can see it in the console, but for some reason, the fetch command isn't passing the data to the view for rendering.

My setup involves using Backbone 1.0.

You can find the code I'm working with on jsbin here: http://jsbin.com/OHePaki/1/edit?html,js,output

// MODELS
var ArtifactModel = Backbone.Model.extend({
    initialize: function() {
        this.on('reset', function(){ artifactView.render() })
    },
    defaults: {
        "text": "Unknown Text",
        "timestamp": "Unknown timestamp"
    }
});
var artifactModel = new ArtifactModel();

// COLLECTIONS
var ArtifactCollection = Backbone.Collection.extend({
    model: ArtifactModel,
    url: '/getDigest.json',
    // url: 'http://we365.local/Artifact/GetShareableArtifact?token=b88d2640826bb8593f6edb308ce604f28225f240&artifact_id=2&social_site=tw&log_inside=&go',
    parse: function(data) {
        console.log('running parse');
        return _.map(data.response.content, _.identity);
    },
    initialize: function(){
        this.on('reset', function(){ artifactListView.render(); }),
        console.log('running init function for ArtifactCollection');
        this.fetch();
        //this.reset(artifactjson, { parse: true });
        console.log(this.toJSON());
    }
});
var artifactCollection = new ArtifactCollection();


// VIEWS
    var ArtifactView = Backbone.View.extend({
        tagName: 'li',
        className: 'single-model',
        render: function(){
            var template = Handlebars.compile($('#stream_getDigest').html());
            this.$el.html(template(this.model.toJSON()));
            return this;
        }
    });

    var ArtifactListView = Backbone.View.extend({
        initalize: function(){
            this.collection.on('add', this.addOne, this);
        },
        render: function(){
            this.collection.forEach(this.addOne, this);
        },
        addOne: function(artifactModel){
            var artifactView = new ArtifactView({model: artifactModel});
            this.$el.append(artifactView.render().el);
        }
    });


// rendering
var artifactView = new ArtifactView({model: artifactModel});
var artifactListView = new ArtifactListView({collection: artifactCollection});

artifactView.render();
artifactListView.render();

$('#list').html(artifactListView.$el.html());

Answer №1

Typically, a jQuery ajax call is executed asynchronously, meaning the code will continue running without waiting for the completion of the .fetch() method. In your scenario, the view is rendered before the collection is fully prepared, resulting in empty data for the view.

To address this issue, you can include jQuery ajax options in the fetch function as shown below ():

...
initialize: function(){
    this.on('reset', function(){ artifactListView.render(); }),
    console.log('running init function for ArtifactCollection');
    this.fetch({async:false});
    console.log(this.toJSON()); //This will log the loaded collection
}
...

Alternatively, you can modify the fetching strategy to benefit from asynchronous loading:

this.fetch().done(function(){
    //Actions to perform after the collection is loaded
});
//Avoid using this within the init function

Answer №2

Setting handlers on the models is crucial. Consider the following example:

friendModel.on('change', function() { friendView.render(); });
friendCollection.on('change', function() { friendListView.render(); });

Alternatively, it would be more efficient to include these lines in the constructors of friendModel and friendCollection (refer to ).

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

What is the best way to retrieve the parameters from the current URL within an Express function on the backend? (details below)

Struggling to articulate my issue here. I'm in the process of creating a straightforward express app that utilizes the omdb API to search for movie titles and display the results. The challenge is that the omdb API returns the results in pages, with 1 ...

Leverage AJAX for real-time Django Model updates

Seeking insights on how to effortlessly update a Django model through AJAX without reloading the page or requiring user input for saving. Various tutorials address fetching data from Django models using AJAX, yet resources on updating models remain scarce. ...

Connecting a shared store to multiple single file components in Vue.js 3 - here's how!

In my Vue.js 3 application, I have several single file components and I am looking for a simple way to manage global state. The documentation on state management is helpful, but it mainly focuses on using a reactive object returned from the data function w ...

Extracting updated dom elements with a query

Within my HTML document, I have a div section containing various form input elements. Using jQuery('#div').html(), I can retrieve the original content of this section. However, when I make changes to the form inputs by entering text or selecting ...

There seems to be an issue with Ajax functionality within the Webix framework

Exploring webix for the first time has been quite an interesting journey. I am carefully following the guidance provided in the getting started document to create my own webix program. By placing my code in an HTML page and two JSON files as instructed, he ...

What could be the reason behind the error message: Uncaught TypeError: $ is not a function?

I've noticed that this question has been asked numerous times before, but unfortunately none of the suggested solutions have worked for me. It seems like the root of the problem lies within the jQuery references, however, I do not possess the knowled ...

Robmongo - combine unique values based on different columns

As a newcomer to robmongo, I've been tasked with writing queries for a collection that includes keys like "userId" and "deviceModel." My goal is to create a query that shows the number of users for each device model. Here is the query I have so far: ...

Reasoning behind splitting this solution into a function utilizing Javascript

Today, while working on a coderbyte problem, I managed to solve it on my own without any outside help, and it felt fantastic. However, upon completion, I realized that I solved it without creating any functions. Rather, I kept referring back to a previous ...

The functionality of ui-router appears to be limited when accessed from a nodejs directory, however, it functions properly on

It's strange that ui-router is not functioning as expected on my computer. The setup involves an index.html file serving as a header and test.html as an attached view. Interestingly, it works perfectly fine on Plunker. The content of index.html match ...

Is the neglected property being discarded?

First things first, let's talk about my class: class FavoriteFooBar { ... isPreferred: boolean = false; constructor() { this.isPreferred = false; } } Using a utility library called Uniquer, I arrange a list of FavoriteFooBar instances to pr ...

VueJS - Display a v-html tag that is initially empty but will eventually show content determined by

I have created a recursive component that is capable of infinitely looping over its children At the top of this component is the following line, which serves as the first element within the Vue component: <component class="relative " :is="type || &apo ...

Working with Facebook Graph API data using javascript

I am attempting to parse output results from the Facebook Graph API (specifically comments on a website). Below is the script I am using: if (document.getElementById('comments')) { var url = "https://graph.facebook.com/fql?q=select+xid%2C ...

Updating state atoms in Recoil.js externally from components: A comprehensive guide for React users

Being new to Recoil.js, I have set up an atom and selector for the signed-in user in my app: const signedInUserAtom = atom<SignedInUser | null>({ key: 'signedInUserAtom', default: null }) export const signedInUserSelector = selecto ...

If I change the request mode to 'no-cors' in my Firebase cloud function, how will it impact the outcome?

After encountering an issue with the Firebase inbuilt password reset functionality, I created a Firebase function to handle OTP verification and password changes based on the correctness of the OTP. The function is designed to validate the OTP provided, ch ...

Is it possible to create a special case for the beforeunload function?

Is there a way to exclude a specific URL or form button from the beforeunload event in JavaScript? I want to exempt them, not as error handling exceptions but to customize how they interact with this event. Here is the relevant JavaScript code: if(loggedi ...

Display multiple React components based on certain conditions

Within my definition object, there are various form types that determine which component to render. For example: const definition = { name: "test", id: 1, form: [ {type: "text"}, {type: "checkbox"}, {type: "radio"}] }; To access the form types, ...

Integrate timestamp addition and editing to JSON data in Twitter using jQuery

After successfully adding a timestamp (the question/problem below) to my code, I am now facing difficulties in formatting it. I am looking to display the timestamp as "14 minutes ago" or at least include the date and time. Can anyone guide me on how to ac ...

Send query string parameters to retrieve data within a specific updatedAt timeframe

How can I retrieve data based on a specified range of month/week/days it was last updated? this.userDetails = async (req) => { try { let updatedAt = req.query.updatedAt let start = moment().startOf('day') let end = ...

Sum values in project pipeline based on conditions with Mongo

I am currently implementing a project pipeline that involves filtering values greater than 100 from fields within an object that is part of an array. Here's an example of the database structure: Database: ---Clients Collection--- client: { _id: ...

Fiddler is indicating that my JavaScript file cannot be found, despite the fact that it is present and functioning correctly as anticipated

In Default.aspx, I have added the following line to my javascript file: <script type="text/javascript" src="../../MyFiles/JavaScript/JavaScript.js" ></script> When testing the website using Fiddler, I repeatedly receive a 404 error indicatin ...