Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting backbone models

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);
like image 431
Chin Avatar asked Jul 22 '26 15:07

Chin


1 Answers

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.

like image 90
Dane O'Connor Avatar answered Jul 25 '26 04:07

Dane O'Connor