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").myAttribute1is 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/