Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 869
Pauly Dee Avatar asked Aug 18 '11 09:08

Pauly Dee


People also ask

Is Backbone JS still used?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.

Is Keydown an event?

The keydown event is fired when a key is pressed. Unlike the deprecated keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.

Which function has to be used when you want to trigger the event only once before being removed?

js Event once() The event once method is just like event on method but it causes the bound callback to only fire once before being removed.


1 Answers

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.

like image 184
fearphage Avatar answered Sep 28 '22 12:09

fearphage