'How to decorate a DOM node's event handler?

How can you decorate a DOM node so that you add an event handler, but within the new handler you can call the previous handler?



Solution 1:[1]

It depends on how you're adding your handlers, of course, but here's one old-fashioned way:

function addClickHandler(nodeId, handler) {
  var node = document.getElementById(nodeId), old = node.onclick;
  node.onclick = function() {
    handler(old);
  }
}

Your handler function would check it's parameter to see if it's not null.

You could of course get as fancy as you wanted to here. Note that most Javascript frameworks actually don't give your event handlers much information about other handlers. Generally it's a fragile pattern to work with that sort of relationship, but I suppose if you set out with a design that regularizes tthe handler setup, it could work fine.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pointy