Skip to content

Instantly share code, notes, and snippets.

@ranelpadon
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ranelpadon/fe40998240ec77a546e4 to your computer and use it in GitHub Desktop.
Save ranelpadon/fe40998240ec77a546e4 to your computer and use it in GitHub Desktop.
Alternative implementations using immediately-invoked function expressions (IIFE) to Mozilla's sample codes for JS Closures in loops .
<html>
<head>
</head>
<body>
<!-- Base DOM markup and code logic here: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Closures -->
<p id="help">Helpful notes will appear here</p>
<p>E-mail: <input type="text" id="email" name="email"></p>
<p>Name: <input type="text" id="name" name="name"></p>
<p>Age: <input type="text" id="age" name="age"></p>
<script>
function showHelp(help) {
document.getElementById('help').innerHTML = help;
}
function setupHelp() {
var helpText = [
{'id': 'email', 'help': 'Your e-mail address'},
{'id': 'name', 'help': 'Your full name'},
{'id': 'age', 'help': 'Your age (you must be over 16)'}
];
for (var i = 0; i < helpText.length; i++) {
var item = helpText[i];
// Alternative 1: Using native JS and IIFE event callback.
document.getElementById(item.id).onfocus = (function(help) {
return function(){
showHelp(help);
};
})(item.help);
// Alternative 2: Using native JS and IIFE wrapper.
(function(help) {
document.getElementById(item.id).onfocus = function() {
showHelp(help);
}
})(item.help);
// Alternative 3: Using native JS and IIFE wrapper (without params).
(function() {
var help = item.help;
document.getElementById(item.id).onfocus = function() {
showHelp(help);
}
})();
// Alternative 4: Using jQuery and IIFE event callback.
jQuery('#' + item.id).focus((function(help) {
return function(){
showHelp(help);
}
})(item.help));
// Alternative 5: Using jQuery and IIFE wrapper.
(function(help) {
jQuery('#' + item.id).focus(function() {
showHelp(help);
});
})(item.help);
// Alternative 6: Using jQuery and IIFE wrapper (without params).
(function() {
var help = item.help;
jQuery('#' + item.id).focus(function() {
showHelp(help);
});
})();
}
}
setupHelp();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment