最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Backbone defaults being referenced on property change - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question asked Oct 6, 2011 at 11:46 MityaMitya 1,0238 silver badges14 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 27

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: [] 
    }; 
}
发布评论

评论列表(0)

  1. 暂无评论