我试图理解模型和视图之间的关系.我已经尝试构建模型和视图来渲染该模型.
我得到了Cannot call method 'toJSON' of undefined我理解的错误,因为模型的实际实例没有被发送到视图.
我觉得视图的初始化中缺少一些东西?
该模型:
var sticky = Backbone.Model.extend({
defaults: {
title:"",
content:"",
created: new Date()
},
initialize: function() {
console.log("sticky created!");
}
});
Run Code Online (Sandbox Code Playgroud)
风景:
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;
}
});
Run Code Online (Sandbox Code Playgroud)
创建视图的新模型和新实例:
var Sticky = new sticky({title:"test"}); …Run Code Online (Sandbox Code Playgroud)