问题
I'm looking for a method to bind many different keys to different actions/functions in my viewmodel.
I've found this example where a binding handler is used to bind actions to the enter-key.
But how do I modify this handler to also support a supplied key-code? I'd like to be able to use the same handler for all kinds of keys and preferably also combined with modifier keys.
ko.bindingHandlers.executeOnEnter = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var allBindings = allBindingsAccessor();
$(element).keypress(function (event) {
var keyCode = (event.which ? event.which : event.keyCode);
if (keyCode === 13) {
allBindings.executeOnEnter.call(viewModel);
return false;
}
return true;
});
}
};
回答1:
You could do something like this:
ko.bindingHandlers.actionKey = {
init: function(element, valueAccessor, allBindings, data) {
var handler = function(data, event) {
var keys = ko.utils.unwrapObservable(allBindings().keys) || [13]; //default to Enter Key
if (!Array.isArray(keys))
keys = [keys];
if (keys.indexOf(event.keyCode) > -1) {
valueAccessor().call(data, data, event);
};
};
var newValueAccessor = function() {
return { keyup: handler };
};
ko.bindingHandlers.event.init(element, newValueAccessor, allBindings, data);
}
};
and you can use this binding in like this:
Observable Keys: <input data-bind="actionKey: action, keys: keyCodes" /><br/>
Inline Keys: <input data-bind="actionKey: action, keys: [33, 34]" /><br/>
Inline Key: <input data-bind="actionKey: action, keys: 33" /><br/>
Default Keys: <input data-bind="actionKey: action" /><br/>
Here is a fiddle demonstrating this binding.
来源:https://stackoverflow.com/questions/15977496/bind-any-key-by-keycode-to-an-action-using-knockout