Create a collection in Backbone consisting of models populated with information sourced from a JSON document

Just starting to dip my toes into the world of Backbone.js and I feel like I'm getting the hang of it.

A little context: I recently built an interactive quiz using jQuery and Handlebars, but now I want to transition it over to Backbone. The Quiz pulls all its questions from a static allQuestions.json file in the same directory. Here's what the file structure looks like:

{
"Q1" : {"question": "Who is the true Admin of the HON chat?",
"choices": ["Kattigpelika", "Bangan", "Naldor"],
"correctAnswer": 0},

"Q2" : {"question":"Who is the chat's true mad son?",
"choices": ["Bangan","Grev3n","Mettapod"],
"correctAnswer": 1
}
ETC...

(The format is correct as I have used it before with $.getJSON)

My current focus is on creating a Model:

var Question = Backbone.Model.extend({
initialize: function(){
    console.log("Model created");
}
});

that integrates into the Collection:

var Questions = Backbone.Collection.extend({
model: Question,
url: "allQuestions.json"
});

I am attempting to use the function:

allQuestions.fetch({
success: function(){
    console.log(allQuestions);
}
});

To generate a new model for each object in the .json file and add it to the collection. Is this doable? Or am I missing something?

All of this is running on my local machine.

Answer №1

The issue does not lie with Backbone, but rather with the format of your JSON object. By making a modification to resemble the following structure, each question will load different models:

[
 {
  "id": "Q1", 
  "question": "Who is the true Admin of HON-chat?",
  "choices": ["Kattigpelika", "Bangan", "Naldor"],
  "correctAnswer": 0
 },
 {
  "id": "Q2", 
  "question":"Who is the chat's true mad son?",
  "choices": ["Bangan","Grev3n","Mettapod"],
  "correctAnswer": 1
 }
]

You can test it out on this JSFiddle link.

Answer №2

To optimize performance, it is recommended to include the data in the initial view response from the web server and render it accordingly (refer to ).

If this is not feasible, you can customize your collection's sync method so that when the method is "read", it utilizes $.getJSON for retrieving data, and falls back to Backbone.sync for other operations.

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 open an already existing tab in Safari using an HTML 'a' link?

Is it possible to return to Safari after launching another app? <a href="webbrowserapp://example.com/open?url=http.....">Open WebBrowserApp</a> I've tried using: <a href="safari://">Return to Safari</a> It would be ideal if ...

Is there a way to prevent on-click errors in ReactJS that someone can share with me?

The onclick listener was expected to be a function, but instead received a value of string type. getListener@http://localhost:3000/static/js/bundle.js:18256:15 accumulateSinglePhaseListeners@http://localhost:3000/static/js/bundle.js:22846:39 <button on ...

Having trouble storing the message ID within the user Object using Mongoose

My goal is to add a message to the messages property (an array) of a user object using Mongoose. However, I encounter an error when trying to save the user (user.save()). To troubleshoot, I added three console.log statements in the code below. Can anyone h ...

Tips for creating a scrolling animation effect with images

I'm currently attempting to create an animation on an image using HTML/CSS. The issue I'm facing is that the animation triggers upon page load, but I would like it to activate when scrolling down to the image. Below is my snippet of HTML: <fi ...

How can I convert a string containing integers into an int[] using javascript or jQuery?

I want to create a feature that allows users to input a list of IDs in a textarea, with the option to separate them by either whitespace or commas. After the user inputs the list, I need to convert it into an int[] array but also throw an error if the str ...

How can I access each element of the array in Java within Android Studio?

When I receive an array of strings in the responseJSON like this: Result: responseJSON = ["Product1","Product2","Product1","Product2"] try { // Invoke web service androidHttpTransport.call(SOAP_ACTION+methName, envelope); // Get t ...

How can I utilize JavaScript on the server-side similar to embedding it within HTML like PHP?

One aspect of PHP that I find both intriguing and frustrating is its ability to be embedded within HTML code. It offers the advantage of being able to visualize the flow of my code, but it can also result in messy and convoluted code that is challenging to ...

Having trouble performing an Image (base64) update in Next.js

Hi everyone, I'm facing a challenge with updating the image data in my code. The base64 string data updates correctly and the new image is displayed before submitting the data. However, once I submit the data, the image doesn't update. Below is ...

Expanding content based on height using React

I have successfully implemented the show more/show less feature. However, my issue is that I would like it to be based on the number of lines or screen height rather than the number of characters. This is because the current setup may look awkward on certa ...

"The challenge of handling multiple HTTP requests in Node.js without receiving proper responses

Hello there, I've been struggling with a Node.js HTTP request issue involving a loop. The loop size is 1728, but the response seems to be missing as it gets stuck at 1727. I've been trying to solve this problem for the past three days with no luc ...

Euler 13: Surprising outcome when attempting to combine several String variables

I'm currently working on a challenging problem found on euler: here Large sum Problem 13 In this problem, the task is to determine the first ten digits of the total sum when adding up one-hundred 50-digit numbers. 37107287533902102798797998220837590 ...

tips for sending the chosen product to axios

How can I send the selected item from the dropdown menu to Axios in order to retrieve data? I need to pass the item itself, not just the ID, to the API. <label>City</label> <select @change="getArea()" v-model="key"> <option :valu ...

Addressing the issue of missing data in JSON documents

Currently, I'm dealing with a situation where my JSON data contains values that are "NULL" from the database. The problem is that these NULL values are being returned as actual NULL values in the JSON response, but I don't want my users to see th ...

You are able to use a null type as an index in angular.ts(2538) error message occurred

onClick() { let obj = { fName: "ali", LName: "sarabi", age: "19", } let fieldName = prompt("field"); alert(obj[fieldName]); } I encountered an issue with the code above where alert(obj[fieldName] ...

Generating JSON data from a loop with refined outcomes

My goal is to iterate through JSON data and extract "time", "blocks" information, while filtering the "amounts" based on a specific variable named _miner. So far, I've successfully retrieved the name, time, and blocks data, but I'm struggling wi ...

Transferring variables between vanilla JS and Angular 2: A guide

I am facing a challenge where I need to retrieve an object title from vanilla JavaScript and then access it in my Angular 2 component. Currently, I am storing the variable in localStorage, but I believe there must be a better approach. The issue arises wh ...

How Kafka Streams Can Divide a Single Stream into Various Streams

As part of a project, I was assigned to learn how to work with Kafka Streams, but I'm encountering a lot of challenges. Currently, I am using kafka-streams version 1.0.1. We have a primary stream with messages in the following JSON format: { "p ...

When the component is initialized, the computed property is not being evaluated

My maps component initializes a Google map, adds markers based on props passed from the parent, and sets the correct bounds of the map. However, the markers are added through a computed property to make it reactive. Everything seems to be working fine, exc ...

What causes the browser to be blocked when using $.getJSON()?

Managing a page that lists hardware devices monitored for customers can be challenging, especially when considering the status of each device. To avoid slow page load times, I have implemented a strategy where the device list is displayed first, and then t ...

Replicate the texture using Three.js

I am seeking to assign the left half of a video texture to the left Geometry and the right half of the video texture to the right Geometry. var video = document.createElement("video"); var texture = new THREE.Texture(video); texture.offset = new THREE.Ve ...