title: Why do new instances of a Backbone.js model contain additional values to the predefined defaults?
body: <p>I am using Backbone.js to create compound form fields which hold a telephone number along with the category of the phone number.  There are two views: one renders the compound field (see PhoneFieldView), while the other renders the fieldset containing the fields (see PhoneFieldSetView). The fieldset view also contains a button for dynamically adding new phone fields.</p>
  
  <p>When PhoneFieldsetView is initialized it reads values from an object in the DOM (var window.Namecards.phone). This is an Array of objects containing values used to populate the field set on initialization (for example when reloading the form if the phone field failed validation, it would reload the previous values and add an error css class). An example DOM Object would be:</p>
  
  <pre><code>window.Namecards.phone = [ 
    {  
      value: '1111111',
      type: 'work',
      cssClass: ['form-field-error']
    }, 
    {
      value: '222222',
      type: 'home',
      cssClass: ['form-field-error']
    }
  ]
  </code></pre>
  
  <p>The problem is that when the PhoneFieldsetView is rendered each call to </p>
  
  <pre><code>var phoneField = new PhoneField(); 
  </code></pre>
  
  <p>results in an instance looking something like this:</p>
  
  <pre><code>phoneField = {
    cssClass: ["phone-number", "form-field-error", "form-field-error"],
    number: "111",
    selectTypeElementName: "phone[type]",
    textInputElementName: "phone[number]",
    type: "home"
  }
  </code></pre>
  
  <p>The problem is with the cssClass property.  As you can see it contains two strings for "form-field-error". Turns out that the number of times the string 'form-field-error' appears in the array cssClass is equal to the number of objects in window.Namecards.phone.  For example if  window.Namecards.phone contains 5 items, then 'form-field-error' will appear 5 times in each instance of PhoneField.</p>
  
  <p>This puzzles me, as according to my understanding, when I call </p>
  
  <pre><code>var phoneField = new PhoneField(); 
  </code></pre>
  
  <p>I should only have the default values for the PhoneField model.  So why are these additional values for cssClass also being added.</p>
  
  <p>Same thing is happening when I add a new blank field to the form (see PhoneFieldsetView.addNewField()). When I create a new instance of the PhoneField model, it also contains additional 'form-field-error' cssClass values.</p>
  
  <p>I am guessing this is an issue with scope, but I can't locate the source. Below is the full code.</p>
  
  <pre class="lang-js prettyprint-override"><code>(function($){
  
    $(document).ready(function() { 
  
      var PhoneField = Backbone.Model.extend({
        defaults: {
          textInputElementName: 'phone[number]',
          selectTypeElementName: 'phone[type]',
          number: '',
          type: 'work',
          cssClass: ['phone-number']
        }
      });
  
      var PhoneFields = Backbone.Collection.extend({
        model: PhoneField
      });
  
      var PhoneFieldView = Backbone.View.extend({
        tagName: 'div',
        events: {
          'click a.delete-phone-number': 'remove'
        },
        initialize: function() {
          _.bindAll(this, 'render', 'remove');
        },
        render: function(counter) {
          var inputCssClass = this.model.get('cssClass').join(' ');
          this.$el.html('&lt;input id="phone-number-' + counter + '" type="text" name="' + this.model.get('textInputElementName') + '" value="' + this.model.get('number') + '" class="' + inputCssClass + '" autocomplete="off" /&gt;' +
              '&lt;select  id="phone-type-' + counter + '" name="' + this.model.get('selectTypeElementName') + '" phone="phone-type"&gt;' +
              '  &lt;option value="work"&gt;Work&lt;/option&gt;' +
              '  &lt;option value="home"&gt;Home&lt;/option&gt;' +
              '  &lt;option value="other"&gt;Other&lt;/option&gt;' +
              '&lt;/select&gt;' +
              '&amp;nbsp;&lt;a href="#" class="delete-phone-number"&gt;Delete&lt;/a&gt;');
          // Select default option.
          this.$('select option[value="' + this.model.get('type') + '"]').attr('selected', 'selected');
          return this;
        },
        remove: function() {
          // Destroy the model associated with this view.
          this.model.destroy();
          // Remove this model's view from DOM.
          this.$el.remove();
        }
      });
  
      var PhoneFieldsetView = Backbone.View.extend({
        el: $('fieldset.phone'),
        events: {
          'click button#add-phone-button': 'addNewField'
        },
        initialize: function() {
          var self = this;
          _.bindAll(this, 'render', 'addField', 'addNewField', 'appendField', 'removeField');
          this.counter = 0;
          this.collection = new PhoneFields();
          // Create initial fields. The variable window.Namecards.phone is set 
          // by the server-side controller.  Note that this is added before binding 
          // the add event to the collection. This prevents the field being appended 
          // twice; once during initialization and once during rendering. 
          if (typeof window.Namecards.phone !== 'undefined') {
            _.each(window.Namecards.phone, function(item, index, list) {
              self.addField(item.value, item.type, item.cssClass);
            });
          }
          // Bind collection events to view.
          this.collection.bind('add', this.appendField);
          this.collection.bind('remove', this.removeField);
          // Render view.
          this.render();
        },
        render: function() {
          var self = this;
          this.$el.append('&lt;legend&gt;Phone&lt;/legend&gt;');
          this.$el.append('&lt;div id="phone-field"&gt;&lt;/div&gt;');
          this.$el.append('&lt;button type="button" id="add-phone-button"&gt;New&lt;/button&gt;');
          _(this.collection.models).each(function(item){ // in case collection is not empty
            self.appendField(item);
          }, this);
        },
        // Add field containing predetermined number and type.
        addField: function(number, type, cssClass) {
          var phoneField = new PhoneField();
          console.log(phoneField.attributes);
          if (typeof number !== 'undefined') { 
            phoneField.set({
              number: number
            });
          };
          if (typeof type !== 'undefined') {
            phoneField.set({
              type: type
            });
          }
          if (typeof cssClass !== 'undefined' &amp;&amp; cssClass.trim() !== '') {
            phoneField.get('cssClass').push(cssClass);
          }
          this.collection.add(phoneField);
        },
        // Add new empty field.
        addNewField: function() {
          var phoneField = new PhoneField();
          console.log(phoneField.attributes);
          this.collection.add(phoneField);
        },
        appendField: function(item) {
          // This appears to be what is binding the model to the view.  
          // In this case it would be binding PhoneField to PhoneFieldView.
          phoneFieldView = new PhoneFieldView({
            model: item
          });
          this.$('#phone-field').append(phoneFieldView.render(this.counter).el);
          this.counter++;
        },
        removeField: function(item) {
          // Create a new field if the last remaining field has been remove.  
          // This ensures that there will always be at least one field present.
          if (this.collection.length === 0) {
            this.addField();
          }
        }
      });
  
      // Create instance of PhoneFieldView.
      var phoneFieldsetView = new PhoneFieldsetView();
  
    });
  
  })(jQuery);
  </code></pre>