Skip to content

Instantly share code, notes, and snippets.

@textarcana
Created October 5, 2009 02:27
Show Gist options
  • Save textarcana/201796 to your computer and use it in GitHub Desktop.
Save textarcana/201796 to your computer and use it in GitHub Desktop.
<html>
<head>
<title>closure capture js example</title>
</head>
<body>
<div id="mydiv"><p>my div</p></div>
<div id="myotherdiv"><p>my other div</p></div>
<script type="text/javascript">
var obj = document.getElementById('mydiv');
obj.onclick = (function () {
var localObj = obj;
return function (){
alert(localObj.id);
}
})();
obj = document.getElementById('myotherdiv');
</script>
<!-- see http://lists.evolt.org/pipermail/javascript/2009-October/013197.html -->
</body>
</html>
/**
* based on the closure capture pattern, one can create factory
* functions quite easily.
*
* Simply replace the JS above with the following...
*/
var handlerFor = function (o){
o.onclick = (function () {
var localObj = o;
return function (){
alert(localObj.id);
}
})();
}
/**
* Now we can use handlerFor to create many onclick handlers.
*/
handlerFor(document.getElementById('mydiv'));
handlerFor(document.getElementById('myotherdiv'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment