I have a simple question about Backbone.js' get and set functions.
1) With the code below, how can I 'get' or 'set' obj1.myAttribute1 directly?
Another question:
2) In the Model, aside from the defaults object, where can/should I declare my model's other attributes, such that they can be accessed via Backbone's get and set methods?
var MyModel = Backbone.Model.extend({
defaults: {
obj1 : {
"myAttribute1" : false,
"myAttribute2" : true,
}
}
})
var MyView = Backbone.View.extend({
myFunc: function(){
console.log(this.model.get("obj1"));
//returns the obj1 object
//but how do I get obj1.myAttribute1 directly so that it returns false?
}
});
I know I can do:
this.model.get("obj1").myAttribute1;
but is that good practice?
While
this.model.get("obj1").myAttribute1
is fine, it's a bit problematic because then you might be tempted to do the same type of thing for set, i.e.But if you do this, you won't get the benefits of Backbone models for
myAttribute1
, like change events or validation.A better solution would be to never nest POJSOs ("plain old JavaScript objects") in your models, and instead nest custom model classes. So it would look something like this:
Then the accessing code would be
but more importantly the setting code would be
which will fire appropriate change events and the like. Working example here: http://jsfiddle.net/g3U7j/
I use this approach.
If you have a Backbone model like this:
You can set the attribute "a.b" with:
Now your model will have attributes like:
with the "change" event fired.
There is one solution nobody thought of yet which is lots to use. You indeed can't set nested attributes directly, unless you use a third party library which you probably don't want. However what you can do is make a clone of the original dictionary, set the nested property there and than set that whole dictionary. Piece of cake.