Search code examples
javascriptphpbackbone.jscollectionsmodels

Adding an array of collections to the Previously added collection in Backbone JS


Hi I am new to Backbone JS and was simply playing around and trying to learn. I am stuck with this for quite some time now. any help will be appreciated, Thanks in advance!

This is my Model

var Human = Backbone.Model.extend({
  defaults: {
    name: 'Fetus',
    age: 0,
    child:'noname'
  },
 });



 var human = new Human();
 human.set({ name: "Thomas", age: 67, child: "Ryan"}); //Works fine

This is my collection

var Person = Backbone.Collection.extend({
  model: Human
});


var Human1 = new Human({ name: "Khaleesi", age: "37", child: "Drogon" });
var Human2 = new Human({ name: "Rahul", age: "25", child: "Rita" });
var Human3 = new Human({ name: "Seema", age: "26", child: "Maruti" });

var thePeople = new Person([ Human1, Human2, Human3]);
document.write("</br>");
document.write(JSON.stringify( thePeople.models )); // This also works fine

I want to add these data to my previous array

var sm = this.Person.add(new Human([
  { name: "Hemath", age: "32", child: "sophie" },
  { name: "Siddharth", age: "26", child: "Tom" }
]));

document.write(JSON.stringify( sm.models ));

Cant really add the next 2 array of data into my collection


Solution

  • You should add array to collection

    var sm = this.Person.add([
      { name: "Hemath", age: "32", child: "sophie" },
      { name: "Siddharth", age: "26", child: "Tom" }
    ]);