A couple of months ago I wrote about Prototype and the This Keyword, and how bind and bindAsEventListener can set what the this keyword will reference. I had assumed that those functions could only be called when the function name is known. For example:

doSomething: function() {
}Event.observe(link, 'click', this.doSomething.bind(this), false);

Well, it turns out that you can attach bind on the end of the function itself. This becomes useful when attaching events to links, like so:

Event.observe(link, 'click', function(){this.doSomething()}.bind(this), false);

Which turns out to be nice, so that we can pass varaiables to functions triggered by an event handler. It also makes dealing with enumerables interesting:

this.viewableFields['all'].each(function(num, index) {

While this seems straightforward now, the syntax is so odd that it never occurred to me. In fact, just after typing the last sentence, I went back and reread Justin’s tutorial on enumerables and realized that he posted the solution for this as well. So, instead of deleting everything I just typed, I’ll post this for those of you who, like me, missed this trick.

HTML Form Builder
Ryan Campbell

Prototype Bind Revisited by Ryan Campbell

This entry was posted 5 years ago and was filed under Notebooks.
Comments are currently closed.


  1. Justin · 5 years ago

    I followed you up to the last example, but had to go read Justin’s tutorial to understand the last bit.

    It would help me a lot to see the enumerable that you’re using as a starting point.

  2. Jasper Jasper · 5 years ago

    Everyone needs a hug.

  3. bear · 5 years ago

    Dude, you rock. This saved my butt!