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() {
alert('hi');
}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) {
this.doSomething();
}.bind(this));
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.
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.
Everyone needs a hug.
Dude, you rock. This saved my butt!