Remove a backbone model by id?

2019-06-14 22:20发布

问题:

Can you remove a model by id? The documentation says you need to pass in the model itself to remove it.

So I need to fetch the model first and then remove it? I can't just remove it by id?

回答1:

Do you mean remove the model from a collection? Looking at the docs, it does seem like you need to pass in a real model, but the source code suggests that you can just pass in either the model id or the model cid as well, and all of the above should work (as well as arrays of all of the above).

So all of the following should be equivalent:

collection.remove(myModel);
collection.remove(myModel.id);
collection.remove(myModel.cid);
collection.remove([myModel]);

I haven't tested this, however.



回答2:

Just stumbled upon this post (don't ask me how), the ID of a model is by default something like c1 or c23. If you wish to remove a model by ID from the collection, then you simply get the model from the collection using:

myCollection.get('c1');

This will return the model with ID c1, if you wish to immediately remove it, you just pass the returned model to the collections remove() function.

myCollection.remove( myCollection.get('c1') );