Module 2: Model 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 Vehicle = Backbone.Model.extend({
    dump: function(){
        console.log(JSON.stringify(this.toJSON()));
    }
});

var v = new Vehicle({type:"car"});

v.on("change", function(){
    console.log("something changed");
});
v.on("change:color", function(){
    console.log("color changed!");
});
v.set("type", "truck");
v.set("color", "deep purple");

// Custom Model Events
var volcano = _.extend({}, Backbone.Events); // adds content of Backbone.Events to an empty object
volcano.on("disaster:eruption", function(options){
    console.log("duck and cover > " + options.plan);
});
// volcano.off("disaster:eruption"); // to remove handler call .off
volcano.trigger("disaster:eruption", {plan:"run"});