Skip to content

Instantly share code, notes, and snippets.

@gavinwilliams
Last active August 29, 2015 13:56
Show Gist options
  • Save gavinwilliams/9272802 to your computer and use it in GitHub Desktop.
Save gavinwilliams/9272802 to your computer and use it in GitHub Desktop.
Angular Keystroke Combo Service
'use strict';
angular.module('MyApp')
.service('Shortcuts', function Shortcuts() {
var _subscribers = {},
_keystrokes = [];
var processKeyStrokes = function processKeyStrokes(keystrokes) {
// Rebuild the hash, this is probably the quickest way to find our subscribers
var keystrokeString = keystrokes.join('');
// Check to see whether the keystroke hash exists in our subscribers list and check the length too
if (typeof _subscribers[keystrokeString] != 'undefined' && _subscribers[keystrokeString].length > 0) {
// Loop through the subscribers for this keystroke hash...
for (var i = 0, j = _subscribers[keystrokeString].length; i < j; i += 1) {
// ... and call them :D
_subscribers[keystrokeString][i].call(null, keystrokes);
}
}
}
window.onkeydown = function listentokeyevents(event) {
// If the keystrokes are empty, listen for a modifier, normally control
if (_keystrokes.length < 1) {
if (event.ctrlKey || event.altKey || event.metaKey || event.shiftKey) {
_keystrokes.push(event.keyCode);
}
return;
}
// Else start building the keystrokes
if (!~_keystrokes.indexOf(event.keyCode)) {
_keystrokes.push(event.keyCode);
}
};
window.onkeyup = function stoplisteningtokeyevents(event) {
// Process the keystrokes
processKeyStrokes(_keystrokes);
// Clear the keystroke history
_keystrokes = [];
};
return {
/**
* Subscribes your callback to an array of keystrokes
* @param {[type]} keystrokes An array of keystrokes starting with a modifier i.e. Shortcuts.subscribe([17, 78], fn) for Ctrl + N
* @param {Function} callback The callback method for the subscriber
*/
subscribe: function(keystrokes, callback) {
// Makes sense to use a hash of the keystrokes here, if we have to search through an array for every subscriber it might get messy!
var keystrokeString = keystrokes.join('');
if (typeof _subscribers[keystrokeString] == 'undefined') {
_subscribers[keystrokeString] = [];
}
_subscribers[keystrokeString].push(callback);
},
/**
* Unsubscribes a callback from all keystroke listeners
* @param {Function} callback [description]
* @return {[type]} [description]
*/
unsubscribe: function(callback) {
// Loop through all of the subscribers
for (var keystrokeString in _subscribers) {
// Loop through the keystroke subscribers
for (var i = 0, j = keystrokeString.length; i < j; i += 1) {
// Find the callback
if (angular.equals(keystrokeString[i], callback)) {
// Delete that bugger
delete keystrokeString[i];
}
}
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment