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