Benjen
Benjen

Reputation: 2925

Why do new instances of a Backbone.js model contain additional values to the predefined defaults?

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.

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:

window.Namecards.phone = [ 
  {  
    value: '1111111',
    type: 'work',
    cssClass: ['form-field-error']
  }, 
  {
    value: '222222',
    type: 'home',
    cssClass: ['form-field-error']
  }
]

The problem is that when the PhoneFieldsetView is rendered each call to

var phoneField = new PhoneField(); 

results in an instance looking something like this:

phoneField = {
  cssClass: ["phone-number", "form-field-error", "form-field-error"],
  number: "111",
  selectTypeElementName: "phone[type]",
  textInputElementName: "phone[number]",
  type: "home"
}

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.

This puzzles me, as according to my understanding, when I call

var phoneField = new PhoneField(); 

I should only have the default values for the PhoneField model. So why are these additional values for cssClass also being added.

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.

I am guessing this is an issue with scope, but I can't locate the source. Below is the full 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('<input id="phone-number-' + counter + '" type="text" name="' + this.model.get('textInputElementName') + '" value="' + this.model.get('number') + '" class="' + inputCssClass + '" autocomplete="off" />' +
            '<select  id="phone-type-' + counter + '" name="' + this.model.get('selectTypeElementName') + '" phone="phone-type">' +
            '  <option value="work">Work</option>' +
            '  <option value="home">Home</option>' +
            '  <option value="other">Other</option>' +
            '</select>' +
            '&nbsp;<a href="#" class="delete-phone-number">Delete</a>');
        // 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('<legend>Phone</legend>');
        this.$el.append('<div id="phone-field"></div>');
        this.$el.append('<button type="button" id="add-phone-button">New</button>');
        _(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' && 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);

Upvotes: 1

Views: 1983

Answers (3)

Benjen
Benjen

Reputation: 2925

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']
    };
  }
});

Upvotes: 2

Jack
Jack

Reputation: 10993

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

Arrays in a Backbone.js Model are essentially static?

Upvotes: 0

JayC
JayC

Reputation: 7141

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 " ".

Upvotes: 2

Related Questions