textarcana (owner)

Revisions

gist: 201796 Download_button fork
public
Public Clone URL: git://gist.github.com/201796.git
Embed All Files: show embed
closure-capture-javascript-example.html #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<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>
handlerFor.js #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* 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'));