I'm struggling to understand how calling destroy
on a model instance is supposed to affect the Model.List it's attached to.
The documentation states that:
One advantage that can.Model.List has over a traditional can.List is that when you destroy a model, if it is in that list, it will automatically be removed from the list.
However when I run this code:
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 + "\"");
Here is what I see in the console:
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"
Why is the element still in the Model.List after calling destroyed? Why aren't the destroyed
and remove
events triggered?
Note that in the real-world code I'm trying to debug, calling destroy
does trigger a DELETE request and the object gets deleted on the server as expected. However it doesn't get removed from the Model.List and therefore neither from the associated view.