Why Do New Instances Of A Backbone.js Model Contain Additional Values To The Predefined Defaults?
Solution 1:
Backbone.js Models works good with value types but I don't know about reference types as I highly doubt it's designed for that. In the line
phoneField.get('cssClass').push(cssClass);
I'm kinda thinking every model instance has a reference to the same array from the default and whatever value is in cssClass is getting pushed to that. Then, when you declare a new PhoneField();
, of course you're getting something weird. As a quick solution I think I'd change the cssClass property of your model to a string (that you consider as an array serialized to it). It shouldn't be to hard to do because "." can't be used as a css Class, so whenever you're assigning it, grab the values and join with a ".", and when you need to use the css classes, split with a "." and then join with a " ".
Solution 2:
After understanding the problem, I can up with the following solution. The trick is to assign a function to the 'defaults' property, which returns the model's default values. Doing so creates a separate instance of the Array ccsClass for each instance of PhoneField.
var PhoneField = Backbone.Model.extend({
defaults: function() {
return {
textInputElementName: 'phone[number]',
selectTypeElementName: 'phone[type]',
number: '',
type: 'work',
cssClass: ['phone-number']
};
}
});
Solution 3:
Essentially you are correct that they are referencing the same array, but you should be able to rewrite it so that each has it's own copy of the array, try assigning the array in the initialize (constructor) function.
You might want to take a look at this question
Post a Comment for "Why Do New Instances Of A Backbone.js Model Contain Additional Values To The Predefined Defaults?"