<!DOCTYPE html>
<
html
>
<
head
>
<
title
>Backbone.js add Collection</
title
>
<
script
src
=
type
=
"text/javascript"
>
</
script
>
<
script
src
=
type
=
"text/javascript"
>
</
script
>
<
script
src
=
type
=
"text/javascript"
>
</
script
>
</
head
>
<
body
>
<
script
type
=
"text/javascript"
>
// 'Food' is a model and that contains the
// default value for the model
var Food = Backbone.Model.extend({
defaults: {
food_region: "India"
}
});
// Here the 'FoodCollection' is a collection instance and model
// 'Food' is specified by overriding the 'model' property
var FoodCollection = Backbone.Collection.extend({
model: Food
});
// The instances "food1" and "food2" are created for
// the model "Food"
var food1 = new Food({
name: "Icecream",
country: "Hyderabad"
});
var food2 = new Food({
name: "cake/chocos",
country: "Guntur"
});
// The add() method adds the models 'food1' and
// 'food2' to the collection instance 'final'
var final = new FoodCollection();
final.add([food1, food2]);
// Display the items in the collection
document.write("Values : ", JSON.stringify(final.toJSON()));
document.write("<
br
>");
document.write("<
br
>");
var food3 = new Food({
name: "fish",
country: "delhi"
});
var food4 = new Food({
name: "onions",
country: "indore"
});
final.add([food3, food4]);
document.write("Values again added: ",
JSON.stringify(final.toJSON()));
</
script
>
</
body
>
</
html
>