0

我是backbone.js(和一般的JS)的新手,并且一直在尝试将模型数据存储在.json文件中。但是我不断收到错误消息:

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();


});
4

1 回答 1

2

您没有将模型的实际实例发送到questionView. 你需要做这样的事情:

render: function() {
    var self = this;
    _.each(this.collection, function(model) {
        var QuestionView = new questionView({ model: model });
        $(self.el).append(QuestionView);
    });
    return this;
}
于 2013-05-08T21:22:35.837 回答