Completely remove attribute from Backbone.js model
Solution 1
The problem is that you're using the parameters for unset
incorrectly. "Silent" should be a part of an options hash, not a separate parameter. This works:
model.unset("AttrName", { silent: true });
The reason for the strange behavior can be seen from the annotated source:
unset: function(attr, options) {
(options || (options = {})).unset = true;
return this.set(attr, null, options);
},
The unset
method assumes that its options
parameter is an object, and attempts to either create or modify it, then passes it on to the set
method. If you pass a string instead, then the inadvertent effect of the code is to set the attribute to null, rather than to unset it.
Solution 2
Override the toJSON method of your model and only include the attributes you wish to send.
Updated: (added code sample)
When extending the model, add a toJSON function and return an object with the desired attributes:
{
toJSON : function() {
return {
name: this.get('name'),
age: this.get('age'),
phoneNumber: this.get('phoneNumber')
};
}
}
FrizbeeFanatic14
I am a Computer Science student at Brigham Young University in Provo, UT, and I work primarily with PHP/MySQL.
Updated on June 05, 2022Comments
-
FrizbeeFanatic14 almost 2 years
I am trying to totally remove an attribute from a backbone model. The model is being sent to an API that isn't very flexible, and it will break if I send additional attributes over the ones I'm supposed to send, so I need to remove an attribute so it no longer exists.
I tried
model.unset
, from this question, but when I print out the object the attribute I'm trying to remove is still listed, just with a value of null.I need the attribute to be completely gone.
My basic structure is:
model.unset("AttrName", "silent");
-
FrizbeeFanatic14 over 11 yearsIf I change the options to be a hash like that it triggers a change event, which is exactly what I'm trying to avoid with the silent option.
-
FrizbeeFanatic14 over 11 yearsI'm pretty new to Backbone - how exactly would I go about that?
-
McGarnagle over 11 years@FrizbeeFanatic14 something else is wrong -- if you use that syntax, it shouldn't raise a change event (I just tested this).
-
FrizbeeFanatic14 over 11 yearsYou're right, it was something else calling that event. Thanks.