Skip to content Skip to sidebar Skip to footer

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}

Solution 1:

Looking at the backbone sourcethis 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.

Post a Comment for "Setting Backbone Models"