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/
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