Javascript Event Handling With prototype’s bind()

• Bill Hunt

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.

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

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