javascript 通过 id 删除主干模型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10400630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:45:27  来源:igfitidea点击:

Remove a backbone model by id?

javascriptbackbone.js

提问by fancy

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

您可以通过 id 删除模型吗?文档说您需要传入模型本身才能将其删除。

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

所以我需要先获取模型然后删除它?我不能只是通过 id 删除它吗?

回答by nrabinowitz

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 idor the model cidas well, and all of the above should work (as well as arrays of all of the above).

您的意思是从集合中删除模型吗?查看文档,您似乎确实需要传入一个真实模型,但是源代码建议您也可以传入模型id或模型cid,并且上述所有内容都应该有效(以及数组以上所有)。

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.

不过,我还没有测试过。

回答by dbf

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

刚刚偶然发现了这篇文章(不要问我如何),model默认情况下a 的 ID类似于c1c23。如果您希望通过 ID 从集合中删除模型,那么您只需使用以下命令从集合中获取模型:

myCollection.get('c1');

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.

这将返回带有 ID 的模型c1,如果您想立即删除它,您只需将返回的模型传递给集合remove()函数。

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

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