Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new models to a backbone collection, not replace

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.

like image 207
CarbonDry Avatar asked Dec 21 '22 01:12

CarbonDry


1 Answers

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'
});
like image 156
Vitalii Petrychuk Avatar answered Dec 28 '22 05:12

Vitalii Petrychuk