javascriptknockout.jsroutedevent

Routed events in Knockout?


Are there any available tweak to make Knockout support routed events?

In my perticular case I want to handle context-menu-events in the root-vm of my view and let any nested vm to set up a context-menu trigger like this:

event: { contextmenu: OnContextMenu }

If the OnContextMenu-handler is not defined on the current vm it should route the event to it's parent-vm and so on until a handler is found.

Currently I have to do like this (which is kind of error prone)

event: { contextmenu: $parents[3].OnContextMenu }

Or are there other ways of doing this allready?


Solution

  • Found a simple solution. I'm using the built-in DOM event bubbling and then on the root-element I catch the event and get the vm using ko.dataFor, like this:

    self.OnContextMenu = function (vm, e) { // the root-vm
      vm = ko.dataFor(e.originalEvent.target);
      if (vm && vm.contextMenu) {
        self.openContextMenu(vm.contextMenu);
      }
    };