0

我正在做一个类似于 Backbone-Todo 的示例应用程序。但是当我在集合上调用破坏时,它会给出错误:

未捕获的类型错误:无法读取未定义的属性“销毁”

我怎么解决这个问题。请建议。

以下是我的方法代码:

$(function(){

var Todo = Backbone.Model.extend({

defaults: function() {
  return {
    title: "empty todo...",
    order: Todos.nextOrder(),
    done: false
  };
}

});


var TodoList = Backbone.Collection.extend({

  model : Todo,

  localStorage: new Backbone.LocalStorage("todos-backbone"),

  done: function() {
    return this.where({done: true});
  },

  remaining: function() {
    return this.without.apply(this, this.done());
  },

  nextOrder: function() {
    if (!this.length) return 1;
    return this.last().get('order') + 1;
  },

  comparator: 'order'   
});

var TodoView = Backbone.View.extend({

  tagName:  "li",

  template: _.template($('#item-template').html()),

  events: {
    "click a.destroy" : "clear"
  },

  initialize: function() {
    this.listenTo(this.model, 'destroy', this.remove);
  },

  render: function() {
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  },

  clear: function(){
    this.model.destroy();
  }
});

var AppView = Backbone.View.extend({

  el: $("#todoapp"),

  statsTemplate: _.template($('#stats-template').html()),

  events: {
    "keypress #new-todo":  "createOnEnter",
    "click #remove-all": "clearCompleted"
  },

  initialize: function() {
    this.input = this.$("#new-todo");
    this.main = $('#main');
    this.footer = this.$('footer');

    this.listenTo(Todos, 'add', this.addOne);
    this.listenTo(Todos, 'all', this.render);

    Todos.fetch();
  },

  render: function() {
    var done = Todos.done().length;
    var remaining = Todos.remaining().length;

    if (Todos.length) {
      this.main.show();
      this.footer.show();
      this.footer.html(this.statsTemplate({done: done, remaining: remaining}));
    } else {
      this.main.hide();
      this.footer.hide();
    }
  },

  createOnEnter: function(e){
    if(e.keyCode != 13) return;
    if (!this.input.val()) return;
    Todos.create({
      title: this.input.val()
    })  
    this.input.val('');         
  },

  addOne: function(todo){
    var view = new TodoView({model: todo});
    this.$("#todo-list").append(view.render().el);
  },

  clearCompleted: function(){
    _.invoke(Todos, 'destroy');
    return false;
  }

});

4

1 回答 1

0

对于这个答案,我假设TodosTodoList. 我还假设你的错误是由你的这个函数触发的AppView

clearCompleted: function(){
  _.invoke(Todos, 'destroy');
  return false;
}

在那里,您试图将您的 Backbone.jsCollection实例视为其本来的样子,一个集合,例如一个列表。但是 Backbone 集合不仅仅是列表,它们是具有属性的对象,该属性models是包含所有模型的列表。因此,尝试在对象上使用下划线invoke (适用于列表必然会导致错误。

不过不用担心,Backbone 巧妙地为它的Modeland实现了许多 Underscore 方法Collection包括invoke. 这意味着您可以像这样为集合中的每个模型调用销毁

SomeCollection.invoke('destroy');

希望这可以帮助!

于 2013-05-13T08:06:36.903 回答