A simple Backbone.js plugin for use in leanback apps, where someone is sat on the couch using a remote control to use your app. It’s open source. You can get it and fork it at Backbone on the Couch on github

Gives you something even your mum can understand.

keypad.bind('key:left', doSomething)

vs

What does the magic number 37 mean?

 switch(e.which)
 {
  case: 37
   doSomething();
   break;
  etc:
  etc:
  andsoon:
 }

Usages

In its simplest form you can do the following:

var keypad = new Backbone.OnTheCouch.KeyEvents();

// listen for any of the commonly used d-pad keys (left, right, up, down, enter, space and escape)
keypad.bind("key:up", function(){//do something on up});

If you’re using an event aggregator or something else. You can have the events trigger on that instead:

var eventAggregator = _.extend({}, Backbone.Events);
var keypad = new Backbone.OnTheCouch.KeyEvents({triggerOn: eventAggregator});

eventAggregator.bind("key:up", function(){//do something on up});

You can also replace the d-pad key defaults and provide your own keys that you want to listen for:

var keypad = new Backbone.OnTheCouch.KeyEvents({keyMaps: [
  new Backbone.OnTheCouch.KeyEvent(188, "key:comma"),
  new Backbone.OnTheCouch.KeyEvent(190, "key:fullstop")
 ]
});

keypad.bind("key:comma", function(){//do something odd});

Example

The plugin came out of the development of the XKCD Couch app, which is also a html5 Boxee app. You can see this plugin at work on XKCD Couch app.

Backbone on the Couch on github