Backbone.js未捕获TypeError:对象[object Object]没有方法'create'

时间:2012-09-05 13:13:04

标签: backbone.js

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

我试图接近这个backbone todo example code

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
  3. 这是我想在这里实现的工作代码:

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

1 个答案:

答案 0 :(得分:2)

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

以下是修复它的代码。

var ToDoList = Backbone.Collection.extend({
  model: ToDo,
  url: '/todos' 
});