Tobias Ritzau
Tobias Ritzau

Reputation: 3327

Cross browser key event handler in Dart

I'm using the M1 release and have written a key handler that looks like this:

void _onKeyPress(KeyboardEvent e) {
  switch (e.keyIdentifier) {
    case KeyName.UP:
    case KeyName.LEFT:
      e.preventDefault();
      prev();
      break;

    case "U+0020": // FIXME Must be a better way, or?
    case KeyName.DOWN:
    case KeyName.RIGHT:
      e.preventDefault();
      next();
      break;
  }
}

It works fine in Chrome, but not in FF or IE. There must be better way to handle the space bar and still keep it in one switch, right? I know that I can look at other fields to get space, but that is not a good alternative either (since then I would split the code into two switch statements.) Any way, the issue with it not working in FF and IE is worse. If I rewrite to use keyCode instead it works fine on all browsers.

void _onKeyPress(KeyboardEvent e) {
  switch (e.keyCode) {
    case 38:
    case 37:
      e.preventDefault();
      prev();
      break;

    case 32:
    case 40:
    case 39:
      e.preventDefault();
      next();
      break;
  }
}

My issue is that I can't find the constants for the virtual key codes. Am I doing something wrong? What is the best way to handle key events cross browser compatible in Dart?

Upvotes: 2

Views: 372

Answers (2)

Shannon -jj Behrens
Shannon -jj Behrens

Reputation: 5030

Based on your question, the other answer, this source code, and this bug (which you should star), here are my recommendations:

  • Use keyCode.
  • Don't be afraid to use use if/else if instead of a switch statement if you need to. JavaScript doesn't have optimized switch statements anyway.
  • Until this bug gets fixed, you should probably just create your own constants.

Updated: This has been fixed.

Upvotes: 1

Eduardo Copat
Eduardo Copat

Reputation: 5151

I think this is a similar problem to this issue. Apparently, the KeyIdentifier returns null on Firefox.

By the way, instead of "U+0020" you could use KeyName.SPACEBAR

Upvotes: 0

Related Questions