0
我是backbone.js(和JS中的一般)的新手,並且一直在將模型數據存儲在.json文件中進行試驗。不過,我不斷收到一個錯誤:Backbone.js - 模型未被傳遞到視圖以供模板使用
Uncaught TypeError: Cannot call method 'toJSON' of undefined
造成的:
var questionView = Backbone.View.extend({
tagName:"div",
className:"question-container",
initialize:function() {
_.bindAll(this, "render");
console.log(this.model); //logs undefined but models are being fetched successfully?
console.log("questionView created");
this.render();
},
render: function() {
var data = this.model.toJSON(); //this line is throwing the error
var source = $("#question-template").html();
var template = Handlebars.compile(source);
$(this.el).html(template(data));
return this;
}
});
我可以在模型是有控制檯中看到,但我不明白我在做什麼錯。
在背景:
$(function() {
//question model
var question = Backbone.Model.extend({
initialize: function() {
console.log("question created");
},
defaults:{
number:"",
title:"",
answerA:"",
answerB:"",
answerC:"",
answerD:""
}
});
//questions collection
var questions = Backbone.Collection.extend({
url:"data/questions.json",
model:question,
initialize: function() {
console.log(this);
}
});
//question View
var questionView = Backbone.View.extend({
tagName:"div",
className:"question-container",
initialize:function() {
_.bindAll(this, "render");
console.log(this.model);
console.log("questionView created");
this.render();
},
render: function() {
var data = this.model.toJSON();
var source = $("#question-template").html();
var template = Handlebars.compile(source);
$(this.el).html(template(data));
return this;
}
});
//questions View
var questionsView = Backbone.View.extend({
el:"#app-view",
initialize: function() {
console.log("questionsView created");
this.collection = new questions();
this.collection.fetch({reset:true});
this.collection.on('reset', this.render, this);
},
render: function() {
var QuestionView = new questionView();
$(this.el).append(QuestionView);
return this;
}
});
var QuestionsView = new questionsView();
});
我試過這個,但仍然得到同樣的錯誤我害怕。 – salmoally 2013-05-08 21:27:48
我寧願代替'_.each(this.collection,fn)'代理版本'this.collection.each(fn)' – roberkules 2013-05-08 21:32:25
謝謝, – salmoally 2013-05-08 21:37:37