JavaScript Closure Syntax

Most documentation regarding JavaScript closures is overly complex and, in my opinion, does a poor job of explaining their use well; so here’s my attempt to dumb it down a little. Here’s the basic syntax for a JavaScript closure.

(function(varToKeepInScope) {
   return function () { alert(varToKeepInScope); };
})(varToKeepInScope);

The purpose of a closure is to allow a variable to maintain its scope when called in the future. This is a common scenario in loops, where a variable needs to be passed to an event handler, but the same variable is updated multiple times during the loop.

For example, imagine that you want to add a mouseover handler to every <a> element on your page so that when the user hovers over a link, the title attribute is displayed as a custom-styled tooltip.

var tooltip;
var anchors = document.getElementsByTagName('a');
for (var n = 0, anchor; anchor = anchors[n++];) {
   tooltip = anchor.getAttribute('title');
   anchor.addEventListener('mouseover', function() {
      showTooltip(tooltip);
   });
}

Unfortunately, the above code will not work, and the same tooltip will display over every link. That’s because the tooltip variable continues to be updated until the end of the loop, and you end up passing its last updated value to the showTooltip() function when the mouseover event is triggered.

Closures work by using an anonymous function to return a new function with a new scope for the variable. Here’s how the code above can make use of a closure to retain the appropriate value of the tooltip.

var tooltip;
var anchors = document.getElementsByTagName('a');
for (var n = 0, anchor; anchor = anchors[n++];) {
   tooltip = anchor.getAttribute('title');
   anchor.addEventListener('mouseover', (function(scopedTooltip) {
      return function () { showTooltip(scopedTooltip); };
   })(tooltip));
}

Very simple and a common use-case for closures.

Ektron Editor Not Showing CSS Classes

After upgrading Ektron 8.0, it’s possible that the eWebEditPro WYSIWYG editor may no longer recognize CSS classes from the applied style sheet, and ¬†instead shows a single “Clear Style” value.

Fortunately, there’s a simple fix. Replace the file at ~/workarea/contentdesigner/ekformsiframe.aspx.cs with the file below. You should notice the update immediately.

Download ekformsiframe.aspx