Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js set model attribute inner field

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

like image 942
Harry Avatar asked Dec 26 '11 11:12

Harry


1 Answers

You 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"});

like image 192
minikomi Avatar answered Nov 15 '22 09:11

minikomi