3

What is the equivalent of this $(document).on('keydown', this.logKey); for Backbone events:{}? I am asking because I rather bind all events at once place rather than put some in the initialize method.

I tried the suggestion here: how to capture the key event from a view ? I.e. events{'keydown' : 'logKey'}. This is not working for me though.

Community
  • 1
  • 1

1 Answers1

5

The CSS selectors defined in the View.delegateEvents() are bounded to the context of View.$el so if you want the View to manage the events on document the View.$el should be document itself:

// code no tested
var DocumentView = Backbone.View.extend({
  el: "document",
  events: {
    "keydown": "theHandler"
  }
})
fguillen
  • 36,125
  • 23
  • 149
  • 210
  • thanks! that's very interesting because I tried `'keydown document':'logkey'` and it didn't work. I guess it has to be at `el: 'document'`. –  Aug 29 '12 at 10:05
  • If the target DOM element of the event is the own root `el` you don't have to specify the DOM element – fguillen Aug 29 '12 at 10:08