在收集时调用destroy

时间:2013-05-13 07:26:25

标签: backbone.js

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

  

未捕获的TypeError:无法读取未定义的属性'destroy'

我该如何解决这个问题。请建议。

以下是我的方法代码:

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

});

1 个答案:

答案 0 :(得分:0)

对于这个答案我假设TodosTodoList的一个实例。我还假设您的AppView

中的此函数触发了您的错误
clearCompleted: function(){
  _.invoke(Todos, 'destroy');
  return false;
}

在那里,你试图将你的Backbone.js Collection实例视为一个集合,例如列表。但Backbone集合不仅仅是列表,它们是具有属性models的对象,该列表包含所有模型。因此,尝试在对象上使用下划线的invoke (which works on lists)必然会导致错误。

但不要担心,Backbone整齐地为其ModelCollectionincluding invoke实施了许多Underscore方法。这意味着您可以为像

这样的集合中的每个模型调用destroy
SomeCollection.invoke('destroy');

希望这有帮助!