Backbone.js: Module 6 Collection Events

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.on("add", function(model, collection){
    console.log(JSON.stringify(model) + " has been added.");
});
collection.on("remove", function(model, collection){
    console.log(JSON.stringify(model) + " has been removed.");
});
collection.on("change", function(model, options){
    console.log(JSON.stringify(model) + " has been changed");
});
collection.on("change:name", function(model, options){
    console.log("The name has been changed.");
});
var fred = new Backbone.Model({name: "Fred", age: 30});
collection.add(fred);
collection.remove(fred);

collection.add(fred);
fred.set("age", 31); // just change will be fired
fred.set("name", "Frederick"); // change and change:name will be fired