Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 806
Matt Grande Avatar asked Nov 02 '22 10:11

Matt Grande


1 Answers

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/

like image 104
nikoshr Avatar answered Nov 09 '22 03:11

nikoshr