javascriptbackbone.jsbackbone.js-collectionsclass-extensions

Backbone JS add extended model to a collection of its inherited model type


I've just started digging into backboneJS, and have built started building a small text app in codepen (http://codepen.io/azaslavsky/pen/fJghE). Everything is going well, except I have one problem: once the user hits the submit button, I'd like for the form container view to:

  1. Parse all of the form fields. These are a variety of model types (The title field, a WYSIWYG text editor, etc), as well as one collection (tagInput.collection - all of the tags that the user has put in)
  2. Create a standardized JSON object of all this data the user has given the app to be passed to the server

Currently, what I'm trying to do to extend Backbone.Model into a new a class, "FormModel," which just contains the default attribute "value." Then, I make a new collection on my main container which includes all of the various models within the container. So, the model of container.collection is FormModel, but all of the actual models I am trying to .add() are extended classes for FormModel. Is this possible? Whenever I try to access the collection, it is always empty! I feel like I am missing some key part of understanding the underlying logic guiding backbone, but I can't exactly say what!

The (what I think is) relevant code is attached below. The full code of my latest version of the my "mini-app" is also linked above:

//LINE 9 in Full Code
// Generic, very simply model type for any type of form entry that we can extend
  var FormModel = Backbone.Model.extend({
    defaults: {
      value: '',
    }
  });

  //Input class definition
  var input = {};
  input.model = FormModel.extend({
    defaults: {
      placeHolder: 'Enter Title Here...',
      class: '',
      warn: 'a title',
      size: '20px'
    }
  });
  input.view = Backbone.View.extend({
    events: {
      'keypress input': 'checkKey',
      'change input': 'updateValue'
    },
    initialize: function() {
      _.bindAll(this, 'render', 'checkKey', 'doSubmit','updateValue');
      this.render();
    },
    render: function() {
      if (this.model.get('class')) {
        $(this.el).addClass(this.model.get('class'));
      }
      $(this.el).append('<div class="clearButton inputClear"></div>');
      $(this.el).append('<input type="text" placeHolder="'+this.model.get('placeHolder')+'" style="font-size: '+this.model.get('size')+'">');
      this.clickable = true;
      return this;
    },
    checkKey: function(e) {
      if (e.keyCode === 13) {
        this.doSubmit();
      }
    },
    doSubmit: function() {
      var thisVal = this.updateValue();
      if (thisVal.length > 0) {
      } else {
        alert('Hey, you need to '+this.model.get('warn')+' before you can submit this post!');
      }
    },
    updateValue: function() {
      var thisVal  = $('input', this.el).val();
      this.model.set('value', thisVal);
      return thisVal;
    },
  });



/*
 *[...]
 */



//LINE 132 in Full Code
//Tag class definition
  var tag = {};
  tag.model = FormModel.extend({
    defaults: {
      title: '',
      exists: false,
      parent: $('#container'),
    }
  });
  tag.view = Backbone.View.extend({
    events: {
      'click .clearButton': 'kill',
    },
    initialize: function() {
      _.bindAll(this, 'render', 'kill');
      this.render();
    },
    render: function() {
      $(this.el).addClass('tagRow');
      $(this.el).html(this.model.get('title'));
      $(this.el).append('<div class="clearButton tagClose"></div>');
      this.clickable = true;
      return this;
    },
    kill: function() {
      if (this.clickable) {
        this.clickable = false;
        var that = this;
        $(this.el).animate({opacity: 0}, 500, function(){
          $(that.el).remove();
          this.model.destroy();
        });
      }
    }
  });
  tag.collection = Backbone.Collection.extend({
    model: tag.model,
  });



/*
 *[...]
 */



//LINE 214 in Full Code
  //Container class definition
  var container = {};
  container.collection = Backbone.Collection.extend({
    model: FormModel
  });
  container.model = Backbone.Model.extend({
  });
  container.view = Backbone.View.extend({
    el: $('body'),
    initialize: function() {
      _.bindAll(this, 'render', 'appendItem', 'newTag', 'makeTagDialog', 'validate');
      this.collection = new container.collection();
      this.fields = [];
      this.render();
    },
    render: function() {
      $('body').append('<div id="container"></div>');
      this.container = $('body #container');

      var title = new input.model({
        placeHolder: 'Enter Title Here...',
        class: 'subArea titleArea',
        warn: 'a title',
      });
      this.appendItem(new input.view({model: title}).el);

      this.appendItem(new editor.view({model: new editor.model()}).el);
      this.makeTagDialog();

      var submitButton = new submit.view({model: new submit.model()});
      this.listenTo(submitButton.model, 'change:counter', this.validate);
      $(this.container).append(submitButton.el);

      return this;
    },
    appendItem: function(view) {
      this.collection.add(view.model);
      $(this.container).append(view);
    },
    makeTagDialog: function() {
      this.container.append('<div class="subArea tagDialog"></div>');
      var tags = $('.tagDialog', this.container);
      tags.append('<div class="tagArea"></div>');
      var tagInput = new input.view({
        model: new input.model({ 
          placeHolder: 'Tag Your Post...',
          class: 'tagInput',
          warn: 'at least one tag',
          size: '16px',
          value: ''
        })
      });
      tagInput.addTag = function() {
        if (this.model.get('value').length) {
          this.collection.add(new tag.model({
            title: this.model.get('value')
          }));
        }
        this.clearInput();
      };
      tagInput.model.on('change:value', tagInput.addTag, tagInput);
      this.appendItem(tagInput.el);
      $('.tagInput .clearButton').css('marginTop', '-2px');

      tagInput.collection = new tag.collection();
      tagInput.collection.on('add', this.newTag);
    },
    newTag: function(model) {
        thisView = new tag.view({model: model});
        thisView.parent = this;
        $('.tagArea', this.container).append(thisView.el);
    },
    validate: function(){
      alert('Form validation launched!');
      var form = [];
      this.collection.each(function(value) {
        form.push(value);
      });
    }
  });

new container.view({model: container.model});
})(jQuery);

Solution

  • The problem lies in appendItem method. You are calling it in this way:

    this.appendItem(new input.view({model: title}).el);
    

    But in this way you are passing as argument the view el, not the view itself, and so the view.model is undefined!

    You should refactor appendItem in this way:

    appendItem: function(view) {
        this.collection.add(view.model);
        $(this.container).append(view.el);
    },
    

    And call it:

    this.appendItem(new editor.view({model: new editor.model()}));