为什么我收到错误:“未捕获的TypeError:对象[object object]没有方法'create'”
我试图接近这个backbone todo example code。
$(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);
});
我有两个错误:
这是我想在这里实现的工作代码:
$(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);
});
答案 0 :(得分:2)
看起来是因为您的ToDoList
正在扩展Backbone.Model。它应该扩展Backbone.Collection。
以下是修复它的代码。
var ToDoList = Backbone.Collection.extend({
model: ToDo,
url: '/todos'
});