I have a model that has more attributes than the default attributes. I need to clear all attributes when guest changes and set back to defaults so I don't carry unnecessary attributes.
Clearing all attributes and setting the defaults back causes an infinite loop because of the change:guest event.
How can I delete all of the attributes except one?
Is there a way not to fire another change event when Model attributes are set back to the defaults?
Or delete anything not listed in the defaults?
Here is my Model
defaults: {
_id: 'id',
first_name: 'first_name',
last_name: 'last_name',
guest: true
}
I listen to 'guest' change event
this.on('change:guest', this.reset);
The change event calls reset to update the Model and obviously this causes an infinite loop.
reset: function() {
var new_defaults = _.clone(this.defaults);
this.clear({silent: true});
this.set(new_defaults);
}
I have made a
resetfunction that you can easily add to a base Backbone model. I go into more details about this solution into another answer.It's better than a simple
.clearfollowed by a.setbecause it merges thedefaultsback into the model, letting any passedattributesto override them like on initialization.Then your model:
This way, you have more flexibility on what happens when
guestchanges with theonGuestChangehandler, which makes it possible to callresethowever you like, here with{ silent: true }option.Proof of concept
You don't need to clone the defaults to use them. If they have an array or nested objects,
defaultsshould be a function returning an object.Then, use
_.resultto call the defaults:_.result(this, 'defaults')like in my reset function. The Backbone documentation ondefaultshas this notice: