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