将 Backbone 模型重置为初始默认值的最简单方法?
我的模型已经有一个 defaults
哈希值。当部分视图/页面被重置时,我希望将模型重置回原始默认值。
目前,我明确地将每个属性设置为其默认值。是否有任何内置功能或 JavaScript/Underscore.js/Backbone.js/jQuery 函数可以用来在单个语句中执行此操作?
My models already have a defaults
hash. When parts of the view/page are reset, I wish to reset the models back to their original defaults.
Currently, I explicitly set each attribute to its default value. Is there anything built in or a JavaScript/Underscore.js/Backbone.js/jQuery function that I could use to do this in a single statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我想出了以下方法:
在
clear()
调用中使用{silent: true}
可确保不触发change
事件;它只会在set()
调用时触发。I came up with the following approach:
Having
{silent: true}
in theclear()
call ensures that thechange
event is not fired; it will be fire only onset()
call.当模型具有非空初始对象属性时,我会执行此操作。
首先,将 defaults 定义为函数
,其次,在需要时将模型重置为默认值
I do this when the model has non-null initial object properties.
first, define defaults as a function
second, when needed to reset model to default
基于 saabeilin 的回答和 Backbone 的注释源,我提供了一个最佳函数来满足重置模型的需要。
可重用重置
以下行确保即使属性作为 undefined
{ test: undefined }
传递,它仍然具有默认值。下面是一个示例:
扩展 Backbone
如果您希望将它用于所有 Backbone 模型,您可以扩展 Backbone 本身:
免责声明:如果您正在编写 JavaScript 库或 Backbone 插件,请不要这样做,因为它可能会这样做与另一个库发生冲突,否则可能会导致与使用您的代码的人预期不同的行为。
Based on saabeilin's answer and Backbone's annotated source, I came with an optimal function to fill the need for resetting a model.
Reusable reset
The following line ensures that even if an attribute is passed as undefined
{ test: undefined }
, it'll still have its default value.Here's an example:
Extending Backbone
And if you want it with all Backbone models, you can extend Backbone itself:
Disclaimer: Don't do this if you're writing a JavaScript lib or Backbone plugin, as it could collide with another lib or it could cause a different behavior than the one expected by the person using your code.
我还考虑过结合使用
model.clear()
和model.set()
。然后我遇到了问题,我现在触发了change
事件两次。调用
model.clear()
时使用silent
选项不是一个选项,因为我还希望在属性被取消设置。我最终添加了一个 model.reset() 方法。它采用新的属性哈希,并使用新属性哈希中不存在的旧属性键的
未定义
值填充该哈希。通过这种方式,您可以重置模型的旧属性,并为每个旧属性和新属性获取有效的
change
事件。I also thought about using
model.clear()
andmodel.set()
in conjunction. Then I ran across the problem, that I trigger thechange
event twice now.Using the
silent
option when callingmodel.clear()
is not an option, because I also want to have achange
event fired, when a property gets unset.I ended up with adding a
model.reset()
method. It takes a new attributes hash and fills this hash withundefined
values for old attributes keys not being present in the new attribute hash.This way you reset the models old attributes and get a valid
change
event for every old and new attribute.用新的空模型覆盖当前模型的值怎么样:
What about overriding the value of current model with a new empty model :
我的解决方案是:
My solutions is: