Disable all attributes immediately

I have a question about Backbone, how can I set all the 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 to strip individual properties one at a time.

Any idea?

Gretz,

+3


source to share


3 answers


From the baseline website:

clearmodel.clear ([options])

Removes all attributes from the model, including the id attribute. Fires a "change" event if no silence is passed as an option.

So, I would do something like:

myModel.clear();

      




If you want to keep the attributes, why not iterate over all of them and set them manually?

$.each(this.model.attributes, function(index, value){
    // set them manually to undefined
});

      

+7


source


I know this is an old post, but I recently ran into a similar problem - basically, that if you do unset one by one, you get multiple events change

, with the model in an intermediate state for each one. For this to happen with the corresponding change events that were released afterwards, you would have to disable them silently one by one and then manually trigger the event change events for each one after unsets. However, if you look at the Backbone code, you can see that a method unset

is just a call set

, with {unset:true}

in parameters. Therefore, you should be able to do this:

model.set({ attr1: undefined, attr2: undefined, attr3: undefined }, { unset: true })

      



I haven't tried this in practice, but it should definitely work in theory. You will receive a series of events change

for each attribute after all unfinished quests have been completed. This approach is a little outside the recommended path as it uses unexposed logic from the Backbone source, but since this particular code has n't changed in several years (and apparently was previously supported as an option set

) it should be safe to use and continue to use ...

+3


source


There is no built-in method to set all properties to undefined while preserving the keys attributes

. The good news is that you can easily create one yourself with a one-line underscore:

Backbone.Model.prototype.clearValues = function(options) {
  this.set(_.object(_.keys(this.attributes), []), options);
}

      

All models will have a method clearValues

:

var model = new Model({
  id:1, 
  foo:'foo', 
  bar:'bar'
});
model.clearValues();

console.log(model.toJSON()); //-> {id: undefined, foo: undefined, bar: undefined} 

      

+1


source







All Articles