bindAsEventListener(thisObj[, arg...]) -> Function

An event-specific variant of bind which makes sure the function will recieve the current event object as the first argument when executing.

If you’re unclear on what “binding” is, check out Function’s API page. If you don’t quite understand what bind() does, check out its specific article.

When you’re creating methods that you want to use as event handlers, you need to get the current event somehow, as well as control the context in which the method will run. bindAsEventListener takes care of both, as it binds the handler to the specified context (thisObj) and makes sure the event object gets passed to the handler when the event actually occurs.

This method also works around the problem in MSIE when using DOM level 0 style of event handling and the event object isn’t passed as the first argument, but has to be read from window.event instead. You can forget about that with this method as you don’t have to do it manually.

You typically use this method in conjunction with Event.observe, and anywhere you need to pass a method as an event listener.


Here is a consolidated example:

var obj = { name: 'A nice demo' };

function handler(e) {
  var tag = Event.element(e).tagName.toLowerCase();
  var data = $A(arguments);
  alert( + '\nClick on a ' + tag + '\nOther args: ' + data.join(', '));

Event.observe(document.body, 'click', handler.bindAsEventListener(obj, 1, 2, 3));
// Now any click on the page displays, the lower-cased tag name
// of the clicked element, and "1, 2, 3".