Pasha Craydon

Recent Posts

Mixing Backbone Events

Backbone allows you to mix your own custom events to bind and trigger.

Example in a require module.

  define(function (require) {
    var Backbone = require('backbone'),
      _ = require('underscore'),
      proxy = {};

     _.extend(proxy, Backbone.Events);

    return proxy;
  });

Somewhere else you can include this and start creating your own triggers.

  define(function (require) {
    var Backbone = require('backbone'),
      proxy = require('js/proxy');

      myfunction = function (msg) {
         console.log(msg);
      };

     proxy.on('myevent', myfunction);
     ...
     proxy.trigger('myevent', 'Lets do some nice stuff');
  });

When myevent is triggered it will pass in ‘Lets do some nice stuff’ to myfunction and output it to the console.

Backbone allows you to pass single and multiple events.

  proxy.on('my_first_event', myfunction);
  proxy.on('my_second_event', myfunction);
  proxy.on('my_third_event', myfunction);

Trigger a single event.

  proxy.trigger('my_second_event', 'Say some nice stuff');

Trigger multiple events.

  proxy.trigger('my_first_event my_second_event my_third_event', 'say this three different times');

You can pass multiple arguments to a single event.

  myfunction = function (do, stuff) {
      console.log('I want to ' + do + ' some ' + stuff);
  };

  proxy.trigger('my_first_event', 'eat', 'candy');

You can pass multiple arguments to multiple events.

  proxy.trigger('my_first_event my_second_event', 'chow', 'food');

There is a catchall where you can listen to all events.

  proxy.on("all", function(event) {
      console.log("The event was " + event);
   });

You can also turn off events.

  proxy.off("my_first_event");

Delegate events

Backbone Views allow you to bind events easily,

  events: {
    'click #clickelement': 'clickedFunction'
  },

Behind the scenes is delegateEvents. So maybe you wanted to make two different types of events, you could do so like this;

  var View = Backbone.View.extend({
     el: '#somehtml',

     clickEvents: {
        'click #clickelement': 'clickedFunction'
     },

     keyEvents: {
        'keyup #keyelement': 'keyedFunction'
     },

     initialize: {
       var navEvents = _.extend(this.clickEvents, this.keyEvents);
       this.delegateEvents(navEvents);
     }
  });