Polymer 2.0 pitfalls: key bindings (Accessibility)

How to add key bindings with ES6 class elements

Over the course of the last weeks, we migrated a couple of large applications from Polymer 1 to Polymer 2. Although most of the migration work was rather mechanical, making key bindings work turned out to be non-trivial.

Elements can bind functions to keys with the Polymer’s IronA11yKeysBehavior, e.g. trigger saving when the user presses <ctrl+enter>.

There is currently no Polymer 2 mixin but the old behavior can be used via the legacy bridge:

class MyElement extends Polymer.mixinBehaviors([
Polymer.IronA11yKeysBehavior,
],
Polymer.Element) {
  static get is() { return 'my-element'; }
  get keyBindings() {
return {
'enter': '_onSearch',
};
}
  _search() {
// Let's search
}
}

Beware: It’s essential to define the keyBindings() method not as static!

Happy coding!

Want to learn more about Polymer? Have a look to all our Medium posts on Polymer.


Photo: Paul Scott