为什么我会收到错误消息:“未捕获的 TypeError:Object [object Object] 没有方法 'create'”
我试图靠近这个主干待办事项示例代码。
$(document).ready(function() {
var ToDo = Backbone.Model.extend({
defaults: { "date": "today",
"task": ""
},
initialize: function() {}
});
var ToDoList = Backbone.Model.extend({
model: ToDo
});
var ToDoListView = Backbone.View.extend({
el: 'body',
initialize: function(myTodoList) {
this.todolist = myTodoList;
this.todolist.bind('change', this.render, this);
},
render: function() {
text = this.todolist.toJSON();
string = JSON.stringify(text);
$(this.el).append(string);
return this;
},
events: {
"keypress #new-todo": "createOnEnter"
},
createOnEnter: function(e) {
if (e.keyCode != 13) return;
if (!$("#new-todo").val()) return;
this.todolist.create({"task": $("#new-todo").val()});
$("#new-todo").val('');
}
});
var todolist = new ToDoList();
var myToDoListView = new ToDoListView(todolist);
});
我在那里犯了两个错误:
- 将 ToDoList 定义为模型而不是集合
- 在集合上使用了 save() 而不是 add(),这触发了对不存在的 URL 的搜索
这是我想在这里实现的工作代码:
$(document).ready(function() {
var ToDo = Backbone.Model.extend({
defaults: { "date": "today",
"task": ""
},
initialize: function() {}
});
var ToDoList = Backbone.Collection.extend({
model: ToDo
});
var ToDoListView = Backbone.View.extend({
el: 'body',
initialize: function(myTodoList) {
this.todolist = myTodoList;
this.todolist.bind('add', this.render, this);
},
render: function() {
text = this.todolist.toJSON();
string = JSON.stringify(text);
$(this.el).append(string);
return this;
},
events: {
"keypress #new-todo": "createOnEnter"
},
createOnEnter: function(e) {
if (e.keyCode != 13) return;
if (!$("#new-todo").val()) return;
this.todolist.add({"task": $("#new-todo").val()});
//this.render();
$("#new-todo").val('');
}
});
var todolist = new ToDoList();
var myToDoListView = new ToDoListView(todolist);
});