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

I just started working with Backbone.js and I think I understood its concept.

Background: I did an interactive quiz with jQuery and Handlebars, which now I want to switch to Backbone. The survey reads all questions from the static allQuestions.json file in the same directory. The file is as follows:

{
"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 is formatted correctly, as I used it before (with $ .getJSON)

Now I am trying to create a model:

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

which is part of the collection:

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

});

I need a function:

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

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

I searched for almost two hours to get the answer to this question, so please tell me if you think the question is too broad.

.

+4
2

, JSON. - , :

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

, JSFiddle.

+1

, -, (. http://backbonejs.org/#FAQ-bootstrap).

sync, , "", $.getJSON, Backbone.sync, .

+1

Source: https://habr.com/ru/post/1529417/


All Articles