I got a question about Backbone, how is it possible to set all attributes of a model to empty?
unsetmodel.unset(attribute, [options])
Remove an attribute by deleting it from the internal attributes hash. Fires a "change" event unless silent is passed as an option.
But this is only meant for unsetting individual properties one by one.
Anyone an idea?
Gretz,
I got a question about Backbone, how is it possible to set all attributes of a model to empty?
unsetmodel.unset(attribute, [options])
Remove an attribute by deleting it from the internal attributes hash. Fires a "change" event unless silent is passed as an option.
But this is only meant for unsetting individual properties one by one.
Anyone an idea?
Gretz,
Share Improve this question asked Feb 8, 2013 at 12:07 Sjaak RusmaSjaak Rusma 1,4344 gold badges23 silver badges36 bronze badges3 Answers
Reset to default 7From Backbone site:
clearmodel.clear([options])
Removes all attributes from the model, including the id attribute. Fires a "change" event unless silent is passed as an option.
So I would do something like:
myModel.clear();
If you want to keep the attributes, why not iterate through all of them and set them manually?
$.each(this.model.attributes, function(index, value){
// set them manually to undefined
});
I know this is an old post, but I recently came across a similar issue - mainly, that if you do unset one-by-one, you get multiple change
events, with the model in an intermediate state for each one. To allow this to happen with the appropriate change events fired afterwards, you would have to unset them silently one-by-one, then manually fire change events for each one after the unsets. However, if you look at the Backbone code, you'll see that the unset
method is really just a call to set
, with {unset:true}
in the options. So you should be able to do this instead:
model.set({ attr1: undefined, attr2: undefined, attr3: undefined }, { unset: true })
I haven't tried it in practice, but it should definitely work in theory. You would get a series of change
events for each attribute, after all of the unsets have pleted. This approach is going a little outside the remended path, since it uses unexposed logic from the Backbone source, but since this particular code hasn't changed in a few years (and actually appeared to be supported as a set
option before that), it should be safe to use and continue using.
There isn't a built-in method to set all properties undefined, while keeping the attributes
keys. Good news is that you can easily build one yourself with a underscore one-liner:
Backbone.Model.prototype.clearValues = function(options) {
this.set(_.object(_.keys(this.attributes), []), options);
}
All models will then have a clearValues
method:
var model = new Model({
id:1,
foo:'foo',
bar:'bar'
});
model.clearValues();
console.log(model.toJSON()); //-> {id: undefined, foo: undefined, bar: undefined}