我到处寻找答案,但对我的发现并不满意。
问题是,我正在做一个来自 Addy Osmani 的教程,以在 Backbone 中制作一个“Todo”应用程序,但是当我查看控制台时,我收到一条错误消息this.model is undefined
。
我什至尝试了这个 SO answer Backbone model error shown in console,但我仍然得到同样的错误。请告诉我有什么问题。
顺便说一句,什么是this.model
或this.collection
?我有一个想法,他们指的是Backbone.Model
,Backbone.Collection
但他们是如何工作的?我问这个是因为在另一个教程中this.collection
并且this.model.models
也未定义,当我明确定义Model
and时Collection
。
非常感谢
JS:
//Model
var Todo = Backbone.Model.extend({
defaults: {
title: 'Enter title here',
completed: true
},
validate: function(attrs) {
if (attrs.title === undefined) {
return 'Remember to enter a title';
}
},
initialize: function() {
console.log('This model has been initialized');
this.on('change:title', function() {
console.log('-Title values for this model have changed');
});
this.on('invalid', function(model, error) {
console.log(error);
});
}
});
//View
var TodoView = Backbone.View.extend({
el: '#todo',
tagName: 'li',
template: _.template($('#todoTemplate').html()),
events: {
'dbclick label': 'edit',
'click .edit': 'updateOnEnter',
'blur .edit': 'close'
},
initialize: function() {
_.bindAll(this, 'render');
this.render();
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
this.input = this.$('.edit');
console.log(this.model.toJSON());
return this;
},
edit: function() {
//do something...
},
close: function() {
//do something...
},
updateOnEnter: function() {
//do something...
}
});
var todoview = new TodoView();
console.log(todoview.el);
//Collection
var TodoList = Backbone.Collection.extend({
model: Todo
});