Backbone.js: Module 6 add() & remove()

by emgee

HTML

<script src="http://documentcloud.github.com/underscore/underscore.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone.js"></script>

JavaScript

var collection = new Backbone.Collection();

collection.add(new Backbone.Model({name: "Fred", age: 30}));
// doesn't have to be a Backbone.Model; collection will transform it into Backbone.Model
collection.add({name: "Barney", age: 27});

console.log(JSON.stringify(collection));

collection.add([
    new Backbone.Model({name:"Wilma", age: 28}),
    new Backbone.Model({name:"Betty", age: 25})
]);

console.log(JSON.stringify(collection));

// 0-based indexing
collection.remove(collection.at(1));
console.log(JSON.stringify(collection));

collection.on("add", function(model, col, options){
    // options no longer has .index property for improved add performance
    console.log("Added " + model.get("name") + " at index " + this.indexOf(model));
});

collection.add({name: "Bam-bam", age: 2});
collection.add({name: "Pebbles", age: 2}, {at: 1});
collection.add({name: "Dino", age: 4}, {at:5, silent:true}); // event not raised
console.log(JSON.stringify(collection));