views:

62

answers:

2

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?

A: 

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.

Pointy
A: 

I assume that you are binding events in the way element.onclick = function () {};.

Yes, you can make a function that wraps previous event handlers and execute them sequentially, e.g.:

function addEvent(el, event, handler) {
  var oldEvent = el['on'+event];
  if (typeof oldEvent != 'function') {
    el['on'+event] = handler;
  } else {
    el['on'+event] = function() {
      oldEvent();
      handler();
    }
  }
}

var el = document.getElementById('el');
addEvent(el, 'click', function () { alert('1'); });
addEvent(el, 'click', function () { alert('2'); });

Check the above example here.

CMS