Backbone:如何使用单个命令更新所有模型的属性
我正在创建一个简单的文件夹列表,单击这些文件夹时将被标记为选中,即它们的模型将其 selected
属性更改为 true。我希望此选择是排他的 - 在将文件夹标记为选择之前,所有其他文件夹应标记为未选择。
是的,我能想到的是循环遍历集合来更改每个模型的属性。有没有一些更简单的方法可以完成这个任务?
I am creating a simple list of folders which when clicked will be marked selected that is their model will have its selected
property changed to true. I want this selection to be exclusive - all other folders should be marked unselected before a folder is marked selected.
Right all I can think of looping through the collection to change the property of every model. Is there some easier way I can accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在我正在进行的一个项目中,我们在集合级别维护“选定”项目。我们添加了
getCurrent()
和setCurrent(model)
方法,并且集合将引发change:selection
事件。这对我们来说非常有效。--编辑:每个请求的代码示例。--
以下是我们为所有集合扩展的 base.collection.js 的一部分。您会注意到,我们可以根据 id 或实际模型设置 current,因此
col.setCurrent(123)
和col.setCurrent(anInstanceOfAModel)
都可以工作。同时为当前模型调用setCurrent
不会触发更改事件In a project I'm working on we maintain the 'selected' item at the collection level. We have added
getCurrent()
andsetCurrent(model)
methods and the collection will raise achange:selection
event. This has worked real well for us.--EDIT: code sample per request.--
The following is part of our base.collection.js which we extend for all our collections. You'll notice that we can set current based on id or the actual model so
col.setCurrent(123)
andcol.setCurrent(anInstanceOfAModel)
both work. Also callingsetCurrent
for a model that is already the current doesn't fire the change event您还可以有一个“状态”对象,在其中存储最后选择的文件夹。
然后,您可以将该集合更改回未选中状态,而无需循环遍历整个集合。
You can also have a "state" object, in which you store the last selected folder.
Then you change that one back to not selected, without having to loop through the entire collection.