Prototype: bindAsEventListener()

I’ve been working on some javascript code for a client site and found a good use for binding event listeners through javascript rather than inline. There are several pages I need to add javascript code to expand each textarea on focus and collapse it on blur. So I wrote this simple function using Prototype:

1
2
3
var expandTextArea = function(event){
    Event.element(event).rows = 10;
}.bindAsEventListener(this);

The part I was unfamiliar with was .bindAsEventListener(this). It comes from the Prototype framework and is defined:

1
2
3
4
5
6
Function.prototype.bindAsEventListener = function(object) {
  var __method = this;
  return function(event) {
    return __method.call(object, event || window.event);
  }
}

While studying this, I found Simon Willison’s A Reintroduction to Javascript. I highly recommend it. At the bottom of his discussion of custom objects, he describes how to use apply() and call(). I’m not sure if my understanding is correct, but it reads to me as:

  • this is passed as the Window object to bindAsEventListener(this)
  • bindAsEventListener() returns a function that when called back by the event
  • attaches expandTextArea(event) (in this case) to object (Window) and then calls the method.

The callbacks and closures are really interesting, if a bit difficult to understand, in Javascript. I welcome comments!

Advertisements

Pages

Categories

Copyright ©2008-2013 James E Orchard-Hays, All Rights Reserved

%d bloggers like this: