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?
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.My solutions is:
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 thesilent
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.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.
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
What about overriding the value of current model with a new empty model :