The event-key
module adds the "key" event for subscribing to keyboard
events triggered by users entering specific keys. The subscription
signature includes a filter configuration that can be used to limit event
triggering based on key codes, shift, ctrl, alt, or meta keys pressed, as
well as specifying the keyboard event (keydown
, keyup
, or
keypress
).
The filtering spec
Example subscriptions might look like this:
// certain keys can be referenced by name input.on('key', saveAndClose, 'enter'); // require modifier keys with +(modifier) Y.one('doc').on('key', composeMail, 'n+ctrl'); // specify the event and key codes datatable.get('contentBox') .delegate('key', moveAround, 'down:37,38,39,40', '.yui3-datatable-liner');
The third argument is the filtering spec. Similar to using the
node.delegate()
method, the callback is only executed if the key event
matches the filter. The supported filter syntax is a string defined like
this:
- (0..1) type followed by a colon
- (0..n) comma separated codes
- (0..n) modifiers, each preceded by "+"
Choo choo!
If you're into railroad diagrams, the filter spec looks like this:
-
"
-
type :
-
code
,
-
+modifier
-
"
Filter tokens
- type
- "down", "up", or "press" for
keydown
,keyup
, andkeypress
. The default iskeypress
. - code
- Any numeric
keyCode
, unicode character, or common key name. - modifier
- "shift", "alt", "ctrl", or "meta". "meta" is the Windows key on Windows-friendly keyboards or the Command key on Apple keyboards. Remember each must be prefixed with "+".
Common keys by name
Certain keys are common enough that referring to them by name is just easier and makes the code more readable. The supported key names are:
Name | e.keyCode |
---|---|
enter | 13 |
esc | 27 |
backspace | 8 |
tab | 9 |
pageup | 33 |
pagedown | 34 |
If any of these are found in the spec, the default type becomes keydown
.
If you have a mind to extend this map, it's stored in
Y.Node.DOM_EVENTS.key.eventDef.KEY_MAP
. For example, to add support for
node.on('key', callback, 'arrowup')
, you'd do:
Y.Node.DOM_EVENTS.key.eventDef.KEY_MAP.arrowup = 38;
Caveats
- You can't yet indicate that modifiers must not be in effect or key combinations must only include those modifiers.
- You can't yet specify types or modifiers on a per-code basis.
-
Though you can specify keys by their common name, the event is not yet
decorated in any way with that common name, so you still have to refer
to the
keyCode
in callback code.