1

为什么我会收到错误消息:“未捕获的 TypeError:Object [object Object] 没有方法 'create'”

我试图靠近这个主干待办事项示例代码

http://jsfiddle.net/GhaPF/4/

$(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);

});

我在那里犯了两个错误:

  1. 将 ToDoList 定义为模型而不是集合
  2. 在集合上使用了 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);

});
4

1 回答 1

2

看起来是因为您ToDoList正在扩展 Backbone.Model。它应该扩展 Backbone.Collection。

这是修复它的代码。

var ToDoList = Backbone.Collection.extend({
  model: ToDo,
  url: '/todos' 
}); 
于 2012-09-05T13:34:37.237 回答