简体   繁体   English

使用来自JSON文件的数据创建模型的Backbone集合

[英]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. 我刚开始使用Backbone.js并且认为我有点理解它的概念。

Backstory: I made an interactive quiz with jQuery and Handlebars that i now want to migrate to Backbone. 背景故事:我用jQuery和Handlebars做了一个交互式测验,我现在想要迁移到Backbone。 The Quiz reads all the Questions from a static allQuestions.json file in the same directory. 测验从同一目录中的静态allQuestions.json文件中读取所有问题。 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) (它的格式正确,因为我之前使用过它(使用$ .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. 为.json文件中的每个对象创建一个新模型并将其放入集合中。 Is this possible? 这可能吗? Where am I thinking wrong? 我错在哪里?

This is ALL done locally on my computer. 这是在我的计算机上本地完成的。

Ideally, you can put the data in the view that gets sent by the web server and load that (see http://backbonejs.org/#FAQ-bootstrap ). 理想情况下,您可以将数据放在由Web服务器发送并加载的视图中(请参阅http://backbonejs.org/#FAQ-bootstrap )。

Otherwise, you need to redefine your collection's sync method so that if the method is "read" you call $.getJSON and otherwise you call Backbone.sync as usual. 否则,您需要重新定义集合的sync方法,以便在方法“读取”时调用$.getJSON ,否则您将像往常一样调用Backbone.sync

The problem here is not Backbone but the structure of your JSON object. 这里的问题不是Backbone,而是JSON对象的结构。 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 . 你可以检查它在这个JSFiddle中工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM