Backbone.js - Adding keydown events when view is active?
Asked Answered
W

1

15

I have a view called gallery that options. I want to listen and act on keydown events when the gallery is rendered (until it's closed).

How do I do this in backbone events? I've tried all variations of 'keydown X':function and none have worked.

Wasson answered 18/8, 2011 at 9:43 Comment(6)
Your gallery is backbone view or standalone html + js?Rowles
show us your selectors for keydown events... i think you binding them to wrong elementsRowles
It's just: events: { 'keypress':'doThis' }Wasson
No selectors. Listen to any keypress.Wasson
Try on render bind event to $(document) and on .remove() make unbind()Rowles
What do mean by "a view called gallery that options"?Gurevich
W
23

I just tested the following and it worked flawlessly:

var view = Backbone.View.extend({
  // ... snip ...
  events: {
    'keyup :input': 'logKey'
    ,'keypress :input': 'logKey'
  }
  ,logKey: function(e) {
    console.log(e.type, e.keyCode);
  }
});

I'd go back and check your code. All events in Backbone are defined as delegates attached to the viewInstance.el element. To unbind the events, call viewInstance.remove() which calls $(viewInstance.el).remove() under the covers and cleans up all the delegated events.

Also note that in some browsers (Firefox I believe) there's a known issue that some keys (like arrow keys) don't bubble and will not work properly with delegated keypress events. If you're catching special keys, you're probably better off using keyup and keydown.

Wacky answered 16/9, 2011 at 18:6 Comment(3)
Isn't this making assumptions that the View in question contains inputs? I think the OP was asking about the case where a particular view is simply rendered -- imagine that there is a lightboxed image or something and you wanted to hook up "Escape" to closing the image...Andriette
You are correct. My solution assumes there are input elements. If you wanted to act on key events anywhere in the view, you just exclude the selector (as the Backbone documentation states). events: {keyup: 'logKey'}Wacky
- I can't get these global keypress/keyup/keydown to work. Is there some other minor detail that I must be forgetting? Could you possibly point to a reference or even a fiddle for more information of the document-wide eventsRecrystallize

© 2022 - 2024 — McMap. All rights reserved.