0

我想从集合中删除一个模型:

var item = new Backbone.Model({
    id: "01",
    someValue: "blabla",
    someOtherValue: "boa"
});

var list = new Backbone.Collection([item]);

list.get("01").destroy();

结果:

项目仍在主干阵列中....

4

2 回答 2

3

我对接受的答案有所保留。当模型被销毁时,“destroy”事件会在该模型所在的任何集合中冒泡。因此,当您销毁模型时,您不必同时从列表中删除该模型。

model.destroy();

应该够了。

查看您的代码,它看起来是正确的:(如果意图是销毁+删除,而不仅仅是删除)

list.get('01').destroy();

Are you sure that your resource is getting properly destroyed? Have you tried placing a success and error callback in your destroy() call to ensure the destroy was executed? For example, if your model URL is incorrect and it can't access the resource, the destroy call would return an error and your collection will still have the model. This would exhibit the symptoms you outline in your question.

By placing the remove() after the destroy call, your collection will definitely remove the model. But that model will still be floating around (still persisted). This may be what you want, but since you're calling destroy() I'm assuming you want to obliterate it completely. If this is the case, while remove seems to work, what it's really doing is masking that your model has been destroyed when in fact it may not.

Thus, this is what I have a feeling is actually happening. Something is preventing the model from being destroyed. That's why when you call destroy(), then check your collection - the model is still there.

I could be wrong though. Could you check this and update your findings?

于 2012-08-25T17:05:41.840 回答
2

您还应该从集合中删除模型。

var model = list.get('01');
model.destroy();
list.remove(model);
于 2012-08-25T16:32:07.937 回答