Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone defaults being referenced on property change

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.

like image 457
Mitya Avatar asked Oct 06 '11 11:10

Mitya


1 Answers

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: [] 
    }; 
}
like image 135
Brian Genisio Avatar answered Sep 28 '22 05:09

Brian Genisio