Reputation: 1107
Can someone explain scope to me in Backbone? Is the best way in the example below to use a get method to retrieve the value of a default variable?
If I don't use the get method, my array comes up as undefined.
App.Models.Site = Backbone.Model.extend({
defaults: {
testArray: [1, 2, 3]
},
initialize: function(){
console.log('initialize', this.testArray); // logs undefined
console.log('initialize', this.get('testArray')); // logs [1, 2, 3]
this.test();
},
test: function(){
console.log('initialize', this.testArray); // logs undefined
console.log('test', this.get('testArray')); // logs [1, 2, 3]
}
});
Upvotes: 2
Views: 219
Reputation: 7141
Several things.
First, in defaults
, you're defining model fields, not (object) fields of your model instance. The model fields are what gets serialized to your data store. Your object fields are just part of your object serving whatever purpose you need them to.
Secondly, I think your defaults might be better written using a method to construct the default values:
....
defaults: function(){
return {
testArray: [1, 2, 3]
};
},
...
So that each model starts with a copy of [1, 2, 3]
instead of each model sharing a reference to one and only array that is [1, 2, 3]
(if any of your models change that array, say if you do this.get('testArray')[0]=4
, suddenly the default values will look very different). That won't ever happen if you only set
the field to a new array value, of course.
Upvotes: 1
Reputation: 16561
You can access the defaults
value with App.Models.Site.prototype.defaults
.
If you use get
(see below) you will retrieve the current testArray
value of your model instance. This will not always be the same across instances.
The model properties are stored inside an .attributes
property of the model instead of the model itself. The only way to retrieve the value of a model property is to use get(propertyName)
.
The reason it's done this way is because set
doesn't just change the value of the object but also triggers events to update the UI with the new value etc. If you could do this.testArray
instead of this.get('testArray')
it would be reasonable that you can also assign values to this.testArray
- but that would break things.
For this reason you also shouldn't use .attributes
to assign values - no event handlers would be triggered.
Upvotes: 1