Reputation: 6907
I would like to know how to best solve this problem, and whether backbone has an approach baked in.
I am extending a model to create a base for other models. I have a property assigned that I want to default to being an object. Of course, when I create new new instances of this model they will both be pointing to the same object. Example:
var A = Backbone.Model.extend({
myvar: {
key1: 'value1'
}
});
// Create new instances
a = new A();
b = new A();
// Set a property on the first instance
a.myvar['key2'] = 'value2';
// The second instance is pointing to the same object
a.myvar === b.myvar;
Is there a way provided by backbone to set default properties as reference variables and for instances not to share the same reference? What is the best approach to solve this issue
thanks!
Upvotes: 0
Views: 44
Reputation: 5631
The easiest thing to do is define the defaults in the initialize()
function:
var A = Backbone.Model.extend({
initialize: function(options){
this.myvar = {
key1: 'value1'
};
}
});
Upvotes: 1