2013-05-08 63 views
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(); 


}); 

回答

2

你不发送模型的实际实例的questionView。你需要做这样的事情:

render: function() { 
    var self = this; 
    _.each(this.collection, function(model) { 
     var QuestionView = new questionView({ model: model }); 
     $(self.el).append(QuestionView); 
    }); 
    return this; 
} 
+0

我试过这个,但仍然得到同样的错误我害怕。 – salmoally 2013-05-08 21:27:48

+0

我宁愿代替'_.each(this.collection,fn)'代理版本'this.collection.each(fn)' – roberkules 2013-05-08 21:32:25

+0

谢谢, – salmoally 2013-05-08 21:37:37