Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a global keypress event listener with Marionette

I am developing an app that I would like to be completely driven by keyboard inputs rather than any mouse clicks. It has been developed using Marionette and whilst I am fully able to respond to events on an input, I am really struggling to respond to events on views that don't contain any inputs.

events: ->
    'keyup #discovery-region' : 'logKey'

logKey: (e) ->
    alert("Key pressed")
    console.log("Key pressed " + e.which)

In my index.html file I have

<div class="discovery" id="discovery-region"></div>

In this circumstance I want to handle controlling keyboard inputs on the discovery region. However I would also like for this region to be removed at a later date and another region be in it's place. Should I create a some global mechanism for handling events?

like image 266
Mr Wilde Avatar asked Oct 24 '25 18:10

Mr Wilde


1 Answers

I managed to archive this by creating a Layout view, inside this Layout I define a region, inside this region I can show what ever view I want and swap them if I need to, In the layout view I also define an event listener for the keyup inside the region. It worked for me, the only trick is that the focus has to be on the Region div. but i think you can add more listeners to your other regions...

var MyLayout = Backbone.Marionette.Layout.extend({
 template: "#layout-template",
 events : {
    "keyup #aRegion" : "test"
 },
 regions: {
   aRegion: "#aRegion"
 },
 test : function () {
  console.log("hi");
}                                             
});

here is the working jsfiddle http://jsfiddle.net/rayweb_on/b7tbX/

I hope this helps.

like image 126
Rayweb_on Avatar answered Oct 26 '25 20:10

Rayweb_on