bindAsEventListener :: Function

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

 

An event-specific variant of bind, which makes sure the function will get the current event object as first argument..

 

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. The W3C-conformant way is for the browser to pass it as first argument to your function. This is well and good, but browsers such as Microsoft Internet Explorer fail to do it, for instance. You have to start jumping through hoops.

 

To spare you this, Prototype lets you bind a function as an event listener. This is still a form of binding, so you need to specify first what object is to be guaranteed as the this reference when the function executes. But here, Prototype guarantees that its first argument will be the current event. Any arguments you specify in the remainder of your call to bindAsEventListener will appear next in the arguments list.

 

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

 

Example

 

Here is a consolidated example:

 

var obj = {

  name: 'A nice demo',

  fx: function(e) {

    var tag = Event.element(e).tagName.toLowerCase();

    var data = $A(arguments).shift();

    alert(this.name + '\nClick on a ' + tag + '\nOther args: ' + data.join(', '));

  }

};

 

Event.observe(document.body, 'click', obj.fx.bindAsEventListener(obj, 123));

// -> Any click on the page displays obj.name, the lower-cased tag name of the 

//    clicked element, and "1, 2, 3".

 


Prototype API 1.5.0 - prototypejs.org