How do i minimize closure while using jQuery.bind?
Can someone tell me what the best practices with jQuery to minimize the effects of closures while doing event binding inside a self executing private function. I've been playing around and haven't found a satisfactory solution. Here is the sample code list below:
The gist is i have a self executing function in private scope and in it i declare vars. eventually i may have another function scope and inside that i start doing bindings on DOM elements. There is a good chance when I do these bindings I will be referencing outer variables and storing these variables as closures attached the to the bindings. My question is how should I set up my code so that my event bindings are as closure free as possible, or at least minimize the effects of closures.
So this is relevant to me b/c I do stuff like this a lot if I write my own jQuery plugin. So in this example when I click my stack trace with have 2 closure scopes. If I hover I am referencing the root variables and have 3 closure scopes. Is it possible to get any type of binding to do just 1 scope? Basically I don't want to include extraneous variables and bloat my memory footprint.
<body>
<div id="clickContainer" style="color:#fff;background:#000;width:100px;">
click container
</div>
<br />
<div id="hoverContainer" style="color:#fff;background:#000;width:100px;">
hover container
</div>
<script type="text/javascript">
- (function() {
- var html = 'this represents html object text, can be long';
- var objPlugin = {message:'represents some plugin object or config'};
-
- // small variable to be referenced later in closures
- var intId = 1235;
-
- $(document).ready(function(){
- var message = 'message';
- var someLongHtml = 'long html long html long html long html';
- var clickContainer = $('#clickContainer');
- clickContainer.bind('click',
- function() {
- message = message + ' referencing outer variable and environment';
-
- alert('this is a click handler');
- });
-
- var hoverContainer = $('#hoverContainer');
- hoverContainer.bind('mouseover',
- function(){
- intId ++;
- alert('hovering over container');
- });
- });
- })();
</script>
</body>