Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7747295
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T10:29:38+00:00 2026-06-01T10:29:38+00:00

I am using Backbone.js to create compound form fields which hold a telephone number

  • 0

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);
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T10:29:39+00:00Added an answer on June 1, 2026 at 10:29 am

    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']
        };
      }
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using backbone and trying to create a new object and I am
I'm using backbone with the backbone-rails gem which does its own templating and project
Im using backbone-tastypie to create a nested resource as so. class ServiceResource(ModelResource): manager =
I'm using WCF to create the REST backend for an app using backbone. WCF
I want to create a tree table to display files using backbone.js + jQuery.
I am using backbone.js on a rails backend with HAML Coffee , which is
I'm using Devise and CanCan to create a backbone.js front-end and Rails 3.0.7 for
Using Backbone.JS, I am able to successfully create new models and save them to
I've just started using Backbone.js. I want to create a Collection and add some
I'm considering using apache solr as the search backbone on my site. Along with

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.