Events and bindings

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 ...

Get KnockoutJS Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.