当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Backbone "remembering" values in properties

问题描述:

I have a basic model:

myTestModel = Backbone.Model.extend({

defaults: {

title: 'My Title',

config: {},

active: 1,

}

})

Nothing special there, however I've noticed values in the config option are remembered between instances. For example:

var test1 = new myTestModel();

test1.set('title', 'A New Title');

test1.get('config').screen_name = 'Joe';

alert( test1.get('title') ); // 'A New Title', expected.

alert( test1.get('config').screen_name ); // 'Joe', expected.

var test2 = new myTestModel();

alert( test2.get('title') ); // 'My Title', expected.

alert( test2.get('config').screen_name ); // 'Joe', NOT expected.

So, why in test2, is the screen_name being preserved from test1? How can I prevent this from happening?

网友答案:

You stumbled upon one of the gotchas in Javascript, as noted in the doc for model.defaults:

Remember that in JavaScript, objects are passed by reference, so if you include an object as a default value, it will be shared among all instances. Instead, define defaults as a function.

You can use a function instead of a hash to set your defaults:

myTestModel = Backbone.Model.extend({
    defaults: function () {
        return {
            title: 'My Title',
            config: {},
            active: 1
        };
    }
});

And a demo http://jsfiddle.net/nikoshr/Y7PYj/

分享给朋友:
您可能感兴趣的文章:
随机阅读: