js knockout hotkey code example
Example: js knockout hotkey
ko.bindingHandlers.hotkey = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var options = ko.utils.unwrapObservable(valueAccessor());
if (typeof options === "object") {
var trigger = ko.utils.unwrapObservable(options.trigger.toLowerCase());
var action = ko.utils.unwrapObservable(options.action);
} else {
var trigger = options;
}
var shift = trigger.indexOf("shift") > -1;
var ctrl = trigger.indexOf("ctrl") > -1;
var alt = trigger.indexOf("alt") > -1;
var key = trigger.substring(trigger.length - 1);
$(document).on("keydown", function (e) {
if (e.shiftKey === shift && e.ctrlKey === ctrl && e.altKey === alt && e.which === key.toUpperCase().charCodeAt(0)) {
if ($(element).hasClass("hotkey-pressed") === true) return;
$(element).addClass("hotkey-pressed");
if (action && typeof action === "function") {
action(element);
} else {
if (element.tagName.toLowerCase() == "input"
|| element.tagName.toLowerCase() == "textarea"
|| element.tagName.toLowerCase() == "select")
$(element).focus();
else
$(element).click();
}
e.preventDefault();
}
});
$(document).on("keyup", function (e) {
$(element).removeClass("hotkey-pressed");
});
}
};