forked from ian7/backbone-shortcuts
-
Notifications
You must be signed in to change notification settings - Fork 1
/
backbone.shortcuts.js
95 lines (84 loc) · 3.49 KB
/
backbone.shortcuts.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
(function () {
var Shortcuts;
Shortcuts = function (options) {
this.cid = _.uniqueId("backbone.shortcuts");
this.initialize.apply(this, arguments);
return this.delegateShortcuts();
};
_.extend(Shortcuts.prototype, Backbone.Events, {
initialize:function () {
},
delegateShortcuts:function () {
var callback, match, method, scope, shortcut, shortcutKey, _ref, _results;
if (!this.shortcuts) return;
_ref = this.shortcuts;
_results = [];
for (shortcut in _ref) {
callback = _ref[shortcut];
if (!_.isFunction(callback)) {
method = this[callback];
if (!method) throw new Error("Method " + callback + " does not exist");
}
else {
method = callback;
}
match = shortcut.match(/^(.*?)\s*(<.*>)?$/);
shortcutKey = match[1];
var element = typeof match[2] === 'undefined' ? null : match[2].replace('>', '').replace('<', '');
scope = 'all';
method = _.bind(method, this);
if (element) {
_results.push(
key(
shortcutKey,
scope,
method,
element,
function (e, localElement) {
if (localElement === 'all') {
return true;
}
if (_.isUndefined($(localElement, this.$el).data('shortcutId'))) {
$(localElement, this.$el).data('shortcutId', _.uniqueId('shortcut'))
}
return $(e.target).data('shortcutId') === $(localElement, this.$el).data('shortcutId');
}
)
);
} else {
_results.push(
key(
shortcutKey,
scope,
method,
element,
function (e, localElement) {
var tagName = (e.target || e.srcElement).tagName;
return !(tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA');
}
)
);
}
}
return _results;
},
undelegateShortcuts:function () {
if (!this.shortcuts) return;
var _ref, shortcut, match, shortcutKey, scope;
_ref = this.shortcuts;
for (shortcut in _ref) {
match = shortcut.match(/^(.*?)\s*(<.*>)?$/);
shortcutKey = match[1];
var element = typeof match[2] === 'undefined' ? null : match[2].replace('>', '').replace('<', '');
scope = 'all';
shortcutKey = shortcutKey.replace(/\s/g, '');
var keys = shortcutKey.split(',');
for (i = 0; i < keys.length; i++) {
key.unbind(keys[i], scope, element);
}
}
}
});
Backbone.Shortcuts = Shortcuts;
Backbone.Shortcuts.extend = Backbone.View.extend;
}).call(this);