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,
From 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 completed. This approach is going a little outside the recommended 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With