我试图理解模型和视图之间的关系。我已经尝试构建一个模型和视图来渲染该模型。
我得到了Cannot call method 'toJSON' of undefined
我理解的错误,因为模型的实际实例没有被发送到视图。
我觉得在视图的初始化中缺少一些东西?
该模型:
var sticky = Backbone.Model.extend({
defaults: {
title:"",
content:"",
created: new Date()
},
initialize: function() {
console.log("sticky created!");
}
});
风景:
var stickyView = Backbone.View.extend({
tagName:"div",
className:"sticky-container",
initialize: function() {
this.render();
console.log("stickyView created!");
},
render: function() {
$("#content-view").prepend(this.el);
var data = this.model.toJSON(); // Error: Cannot call method 'toJSON' of undefined
console.log(data);
var source = $("#sticky-template").html();
var template = Handlebars.compile(source);
$(this.el).html(template(data));
return this;
}
});
创建视图的新模型和新实例:
var Sticky = new sticky({title:"test"});
var StickyView = new stickyView();