Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js set model internal attributes hash directly

Tags:

backbone.js

Using Backbone.js I know it's highly recommended to set a model's property using the set method, and NOT by directly modifying the attributes internal hash.

However, apart from not firing the "change" event automatically, what other cons or "side-effects" are there in modifying the internal hash directly?

The problem I'm facing is that while the set method takes an object literal, I need to assign the left hand side using a variable determined at run-time. Thanks.

myModel.set({
    myProperty : myValue; //myProperty is a variable, so this is invalid syntax
})

//vs

myModel.attributes[myProperty] = myValue; //myProperty is a variable that can be evaluated
like image 933
fortuneRice Avatar asked Sep 13 '11 22:09

fortuneRice


Video Answer


2 Answers

Well, if you look at the annotated source code, you'll find that set does a lot.

What if you extended Backbone.Model with a function that does it for you:

Backbone.Model.prototype.setByName = function(key, value, options) { 
    var setter = {}; 
    setter[key] = value; 
    this.set(setter, options); 
};

Then, you can just do what you want directly on the model:

var model = new Backbone.Model();
model.setByName(myProperty, "bar");

That feels like a better solution to me.

Edit

As @earl3s pointed out, this is no longer necessary in more recent versions of Backbone. Today, you can just call model.set(myProperty, "bar") and it does what you want.

like image 58
Brian Genisio Avatar answered Sep 18 '22 06:09

Brian Genisio


In the annotated source code mentioned by Brian Genisio you can read the following lines: "Handle both "key", value and {key: value} -style arguments.". So you can just use model.set(myProperty,"bar",options). Perhaps they've added this feature after the post of Brian Genisio.. i dunno.

like image 32
qbolec Avatar answered Sep 20 '22 06:09

qbolec