I have the following scenario in a backbone view. I wish to set the model like so.
saveField : function(field, val){
//field = 'username'; val = 'Boris'
model.set({field : val});
}
The field is a string representation of an attribute in the model.
The problem is that backbone is creating a new attribute by the name of field. I can set it like so
model.attributes[field] = val;
However, I'd rather use set.
Anyone know how I could do this? thanks
edit: Ended up doing -
var asObj = new Object;
asObj[field] = val;
model.set(asObj);
Looking at the backbone source this should already work - your call just needs to look a little different.
saveField : function(field, val){
//field = 'username'; val = 'Boris'
model.set(field, val);
}
The argument format you're looking for is set(key, value, options). This means you can only set one attribute at a time, but it looks like that's all you want to do. The alternative format is set(attr, options), which is what you were using but doesn't work with string keys.
Regardless, you don't want to set the attribute directly as backbone uses this hook internally to do things like raise the 'changed' event.
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