我試圖通過潛入並構建一個簡單的「問題」應用程序來學習Backbone,但我一直在撞牆試圖弄清楚如何正確使用模型和/或集合。我已經將代碼添加到了我自己迷失的地方。我能夠得到集合拉入JSON文件(做「var list = new QuestionList; list.getByCid('c0')似乎返回第一個問題),但我無法弄清楚如何更新模型,使用當前模型的視圖的數據,然後如何更新模型與下一個問題,當點擊「下一步」按鈕。使用帶有靜態JSON的Backbone.js模型/集合
我想要在這裏是一個簡單的應用程序,拉達負載的JSON,顯示的第一個問題,則顯示了當按鈕被按下的下一個問題。
誰能幫我點連接起來?
/questions.json
[
{
questionName: 'location',
question: 'Where are you from?',
inputType: 'text'
},
{
questionName: 'age',
question: 'How old are you?',
inputType: 'text'
},
{
questionName: 'search',
question: 'Which search engine do you use?'
inputType: 'select',
options: {
google: 'Google',
bing: 'Bing',
yahoo: 'Yahoo'
}
}
]
/app.js
var Question = Backbone.Model.Extend({});
var QuestionList = Backbone.Collection.extend({
model: Question,
url: "/questions.json"
});
var QuestionView = Backbone.View.extend({
template: _.template($('#question').html()),
events: {
"click .next" : "showNextQuestion"
},
showNextQuestion: function() {
// Not sure what to put here?
},
render: function() {
var placeholders = {
question: this.model.question, //Guessing this would be it once the model updates
}
$(this.el).html(this.template, placeholders));
return this;
}
});
感謝一噸的例子!那麼,在這種情況下,使用集合的優勢在哪裏呢?我的意思是,我不能用我自己的ajax調用做同樣的事情並緩存結果嗎?我看到他們和模型的所有示例似乎都將注意力集中在將數據保存到服務器上。這是唯一的用例嗎? – Brian