Adding new models to a backbone collection, not replace

16,550

It happens because you update current model instead of adding new new one. To fix it you have to just execute add method on your collection. This method adds passed data as a new model to your collection:

this.stories.add({
  'title': 'This is my collection test ' + this.options.x,
  'description' : 'this is the description'
});
Share:
16,550
CarbonDry
Author by

CarbonDry

Designer & FrontEnd Developer

Updated on June 04, 2022

Comments

  • CarbonDry
    CarbonDry about 2 years

    I am trying to add new models to a collection (i'm not saving to the server this time, just doing this in memory). I have the code below:

    $(function () {
    
    //Model
    
    var Story = Backbone.Model.extend({
    
      defaults: {
        'title': 'This is the title',
        'description': 'Description',
        'points': 0
      },
    
      url: '/'
    
    });
    
    //Collection
    
    var Stories = Backbone.Collection.extend({
    
      model: Story,
    
      url: '/'
    
    });
    
    //View
    
    var BaseView = Backbone.View.extend({
    
      el: $('#container'),
    
      events: {
        'click .inner': 'onClickInner'
      },
    
      onClickInner: function() {
    
        this.options.x++;
    
        this.story.set({
          'title': 'This is my collection test ' + this.options.x,
          'description' : 'this is the description'
    
        });
    
        this.stories.add(this.story);
    
        this.render();
    
      },
    
      initialize: function () {
    
        this.stories = new Stories();
        this.story = new Story();
    
      },
    
      render: function(){
    
          console.log(this.stories);
    
      }
    
    });
    
    //Initialize App
    
      var app = new BaseView({
        'x' : 0
      });
    
    });
    

    My question is this, for each time 'onClickInner' runs, I want to add a new model to the collection. However, in my code it replaces the existing model in the collection. How do I add new models and not replace?

    Thanks for your time.