I have the following model:
var Soq = Backbone.model.extend({
default:{
'name': 'something'
, 'parents': [] //array will be passed by reference to attributes hash on new object instantiation
}
});
I am new to javascript and backbone but looking at the source I think what might be happening is that when this model's attributes get set to the defaults (backbone.js: 137) and the default value is an object it is done by reference. This means that when I do something like this:
var soq = new Soq;
var parents = soq.get('parents');
parents.push('parent'); //changes defaults of the proto object
var soq2 = new Soq;
console.log(soq2.get('parents');); //will output ['parent']
console.log(soq2.defaults.parents); //will output ['parent']
Am I understanding this correctly, and if so what is the best way to set default values that are objects without making them subject to change anytime a future instance references them?
Let me know if I am being unclear or misunderstanding something. Thanks in advance for your time.
Your "parents" property will be the same on every instance because it is set on the prototype. In other words, the same object will be used to set the model when it gets constructed, therefore you will get the same reference of the array.
Instead, you want to create a new defaults object every time a new model is constructed. Backbone allows you to define your defaults as a function instead:
defaults: function() {
return {
name: 'something',
parents: []
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With