2
Copyright (c) 2010, Yahoo! Inc. All rights reserved.
3
Code licensed under the BSD License:
4
http://developer.yahoo.com/yui/license.html
8
YUI.add('event-key', function(Y) {
11
* Functionality to listen for one or more specific key combinations.
13
* @submodule event-key
17
* Add a key listener. The listener will only be notified if the
18
* keystroke detected meets the supplied specification. The
19
* spec consists of the key event type, followed by a colon,
20
* followed by zero or more comma separated key codes, followed
21
* by zero or more modifiers delimited by a plus sign. Ex:
22
* press:12,65+shift+ctrl
25
* @param type {string} 'key'
26
* @param fn {function} the function to execute
27
* @param id {string|HTMLElement|collection} the element(s) to bind
28
* @param spec {string} the keyCode and modifier specification
29
* @param o optional context object
30
* @param args 0..n additional arguments to provide to the listener.
31
* @return {Event.Handle} the detach handle
33
Y.Env.evt.plugins.key = {
35
on: function(type, fn, id, spec, o) {
36
var a = Y.Array(arguments, 0, true), parsed, etype, criteria, ename;
38
parsed = spec && spec.split(':');
40
if (!spec || spec.indexOf(':') == -1 || !parsed[1]) {
41
a[0] = 'key' + ((parsed && parsed[0]) || 'press');
42
return Y.on.apply(Y, a);
45
// key event type: 'down', 'up', or 'press'
48
// list of key codes optionally followed by modifiers
49
criteria = (parsed[1]) ? parsed[1].split(/,|\+/) : null;
51
// the name of the custom event that will be created for the spec
52
ename = (Y.Lang.isString(id) ? id : Y.stamp(id)) + spec;
54
ename = ename.replace(/,/g, '_');
56
if (!Y.getEvent(ename)) {
58
// subscribe spec validator to the DOM event
59
Y.on(type + etype, function(e) {
62
var passed = false, failed = false, i, crit, critInt;
64
for (i=0; i<criteria.length; i=i+1) {
66
critInt = parseInt(crit, 10);
68
// pass this section if any supplied keyCode
70
if (Y.Lang.isNumber(critInt)) {
72
if (e.charCode === critInt) {
78
// only check modifier if no keyCode was specified
79
// or the keyCode check was successful. pass only
80
// if every modifier passes
81
} else if (passed || !failed) {
82
passed = (e[crit + 'Key']);
87
// fire spec custom event if spec if met
96
// subscribe supplied listener to custom event for spec validator
97
// remove element and spec.
101
return Y.on.apply(Y, a);
106
}, '3.2.0' ,{requires:['node-base']});