I want to set an attribute of a backbone.js model, but only an inner field rather than the entire field.
Example code might be:
model.set('user.avatar', 'img')
Anything I can do?
Thanks
I want to set an attribute of a backbone.js model, but only an inner field rather than the entire field.
Example code might be:
model.set('user.avatar', 'img')
Anything I can do?
Thanks
Share Improve this question asked Dec 26, 2011 at 11:00 HarryHarry 54.9k76 gold badges185 silver badges270 bronze badges1 Answer
Reset to default 21You could simply make a copy of the object, set the attribute, and then re-set it on the original model:
var userAttributes = model.get("user");
userAttributes.avatar = "img";
model.set("user", userAttributes)
Or add a function to set parts of the user on the model from an object:
model = Backbone.Model.extend({
...
setUser: function(attributes){
var user = this.get("user") || {};
_.extend(user, attributes);
this.set({user:user});
},
...
Then pass in attributes like so: model.setUser({avatar: "img"});