Javascript Event Handling With prototype’s bind()

In Javascript, the native event handlers have the infuriating problem of not allowing the user to pass in additional parameters. Normally, when you want to handle an onclick or the like, you can only reference this (meaning the event itself). So everything you want to handle, you have to create a completely isolated custom function for. Not at all efficient. The Prototype library provides a solution.

I recently discovered that Prototype (and by extension, Scriptaculous) has a useful workaround for this problem using it’s bind() function. This function allows you to bind to a function an object to use as the scope of operation. Meaning, if you call it within an object and add bind(this) to your function call, everything within the function is treated as part of the calling object, not the function.


item.addEventListener('mousedown',
function(event) {
this.obj.addClassName('suggest_found');
this.hide();
}.bind(this)
);

And thus, your event handlers are actually made relevant to what you’re calling, instead of being arbitrary and orphaned chunks of code.