0

我很难理解调用destroy模型实例应该如何影响它所附加的 Model.List 。

该文件指出:

can.Model.List 相对于传统 can.List 的一个优点是,当您销毁模型时,如果它在该列表中,它将自动从列表中删除。

但是,当我运行此代码时:

var Todo = can.Model.extend({
  destroy: function() {
    console.log("Calling destroy function");                                            
    return can.Deferred();
  }       
},{})   

Todo.bind("destroyed", function(ev, todo) {                                             
   console.log("Todo \"" + toto.name + "has been destroyed");                           
}); 


var todo1 = new Todo({ name: "Do the dishes", id: 1 });                                 
var todo2 =   new Todo({ name: "Wash floors", id: 2 });                                 
var todos = new can.Model.List([todo1, todo2]);                                         

todos.bind("remove", function( ev, oldVals, indx ) {                                    
  console.log("todo"+indx+" removed")
})         

console.log("Before destroy I have " + todos.length + " elements");                     
console.log("First element is \"" + todos[0].name + "\"");                              
var destroyed = todos[0].destroy()
console.log("After destroy I have " + todos.length + " elements");                      
console.log("First element is \"" + todos[0].name + "\"");

这是我在控制台中看到的:

Before destroy I have 2 elements
First element is "Do the dishes"
Calling destroy function
After destroy I have 2 elements
First element is "Do the dishes"

为什么调用destroyed后元素还在Model.List中?为什么不触发destroyedand事件?remove

请注意,在我尝试调试的实际代码中,调用destroy确实会触发 DELETE 请求,并且该对象会按预期在服务器上被删除。但是,它不会从 Model.List 中删除,因此也不会从关联的视图中删除。

4

1 回答 1

2

通过在模型定义中声明 destroy 方法,您将覆盖默认的 destroy 方法,该方法负责从列表中删除元素。所以你需要从那里删除那个方法,或者调用 super.

这是一个显示此工作的小提琴 http://jsbin.com/zunox/1/edit

于 2014-02-24T02:11:09.697 回答