Created
October 5, 2009 02:27
-
-
Save textarcana/201796 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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