Simple Event Dispatching with Backbone

by robdodson

HTML

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

JavaScript

var dispatcher = {};
_.extend(dispatcher, Backbone.Events);

var receiver = {
    initialize: function() {
        dispatcher.on('hello', this.sayHello, this);
    },
    sayHello: function() {
        console.log('hello!');
        // kill the listener so we only get called once
        dispatcher.off('hello', this.sayHello, this); 
    }
};

receiver.initialize();
dispatcher.trigger('hello');
dispatcher.trigger('hello');