We can wrap events and custom events inside bindingHandlers
. Suppose we want filter products just when we press the Enter key. This allows us to reduce the calls we make to the filter method, and if we are making calls to the server, this practice can help us reduce traffic.
Define the custom binding handler in the custom/koBindings.js
file:
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; }); } };
Since this is an event, we should remember that event initialization can be set in the init
method itself. We catch the keypress
event with jQuery and track the key that has been pressed. The key code for the Enter key is 13. If we...