Search code examples
javascriptjsonbackbone.jshandlebars.js

Make a Backbone collection of models with data from a JSON file


i just got started with Backbone.js and think i've kinda understood the concept of it.

Backstory: I made an interactive quiz with jQuery and Handlebars that i now want to migrate to Backbone. The Quiz reads all the Questions from a static allQuestions.json file in the same directory. The file looks like this:

{
"Q1" : {"question": "Vem är HON-chattens true Admin?",
"choices": ["Kattigpelika", "Bangan", "Naldor"],
"correctAnswer":0},

"Q2" : {"question":"Vem är chattens true mad son?",
"choices": ["Bangan","Grev3n","Mettapod"],
"correctAnswer":1
}
ETC...

(It's correctly formatted as i have used it before (with $.getJSON)

I am now trying to make a Model:

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

that is part of the Collection:

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

});

I want the function:

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

To create a new model for every object in the .json file and put it into the collection. Is this possible? Where am I thinking wrong?

This is ALL done locally on my computer.


Solution

  • The problem here is not Backbone but the structure of your JSON object. If you can modify it to something like this, it would load different models for every question:

    [
     {
      "id": "Q1", 
      "question": "Vem är HON-chattens true Admin?",
      "choices": ["Kattigpelika", "Bangan", "Naldor"],
      "correctAnswer":0 
     },
     {
      "id": "Q2", 
      "question":"Vem är chattens true mad son?",
      "choices": ["Bangan","Grev3n","Mettapod"],
      "correctAnswer":1
     }
    ]
    

    You can check it working in this JSFiddle.