Thursday, April 25, 2024
 Popular · Latest · Hot · Upcoming
110
rated 0 times [  117] [ 7]  / answers: 1 / hits: 16652  / 11 Years ago, sun, august 18, 2013, 12:00:00

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.


More From » backbone.js

 Answers
41

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

[#76294] Friday, August 16, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marcos

Total Points: 331
Total Questions: 106
Total Answers: 104

Location: Gabon
Member since Sat, Jul 25, 2020
4 Years ago
marcos questions
Thu, Feb 24, 22, 00:00, 2 Years ago
Sat, Apr 17, 21, 00:00, 3 Years ago
Mon, Feb 1, 21, 00:00, 3 Years ago
Tue, Jan 26, 21, 00:00, 3 Years ago
Wed, Jan 6, 21, 00:00, 3 Years ago
;