Tuesday, June 28, 2011

Javascript closures

A couple of days ago, there was a thread on Hacker News regarding Javascript closures. The thread referenced a question on Stack Overflow asking how best to explain closures. I'm not going to try and explain them here, but instead describe when the light bulb finally went off in my head regarding closures.

For one of my web app projects, I needed a small component to display the number of characters being typed into a text field (a la Twitter). Unfortunately, I didn't think to check for any existing jQuery plugins for such functionality as there are quite a few. Fortunately, I just rolled my own and in the process finally realized the power of closures.

My implementation turned out to be:


this.AddCharacterCounter = function(textField, counterField, characterLimit)
{
var updateCounter = function()
{
// All the code here to count characters and set css styles
// based on whether or not the limit had been reached.
};

var handleKeyEvent = function(event)
{
updateCounter(textField, counterField, characterLimit);
};

textField.keydown(handleKeyEvent);
textField.keyup(handleKeyEvent);
updateCounter();
}


Then for any field that I wanted to attach such a counter, I just had to do the following:


that.AddCharacterCounter($('#field1'), $('#field1Counter'), 300);
that.AddCharacterCounter($('#field2'), $('#field2Counter'), 150);
that.AddCharacterCounter($('#field3'), $('#field3Counter'), 30);

No comments: