2012-10-18 94 views
1

我試圖通過潛入並構建一個簡單的「問題」應用程序來學習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; 
    } 
}); 

回答

2

很明顯,在當前設置中,視圖需要訪問不僅僅是其單個模型更大範圍。我可以看到兩種可能的方法。

1)將收集品(使用new QuestionView({ collection: theCollection }))而不是型號傳遞給QuestionView。維護一個索引,您可以在click事件中增加和重新呈現索引。這應該是這個樣子:

var QuestionView = Backbone.View.extend({ 

    initialize: function() { 
    // make "this" context the current view, when these methods are called 
    _.bindAll(this, "showNextQuestion", "render"); 
    this.currentIndex = 0; 
    this.render(); 
    }  
    showNextQuestion: function() { 
    this.currentIndex ++; 
    if (this.currentIndex < this.collection.length) { 
     this.render(); 
    } 
    }, 
    render: function() { 
    $(this.el).html(this.template(this.collection.at(this.currentIndex))); 
    } 
}); 

2)建立Router和click事件調用router.navigate("questions/" + index, {trigger: true})。這樣的事情:

var questionView = new QuestionView({ collection: myCollection }); 

var router = Backbone.Router.extend({ 
    routes: { 
     "question/:id": "question" 
    }, 

    question: function(id) { 
     questionView.currentIndex = id; 
     questionView.render(); 
    } 
}); 
+0

感謝一噸的例子!那麼,在這種情況下,使用集合的優勢在哪裏呢?我的意思是,我不能用我自己的ajax調用做同樣的事情並緩存結果嗎?我看到他們和模型的所有示例似乎都將注意力集中在將數據保存到服務器上。這是唯一的用例嗎? – Brian

相關問題