title: Javascript closure behaves differently when bound to an event
body: <p>I am trying to use a closure to ensure that a function can only execute once.  Sounds simple, and it works like this:</p>
  
  <pre><code>function runOnce(fn)  // returns copy of fn which can only execute once
  {
      var ran = false;
  
      return function() 
      {
          if (!ran)
          {
              fn();
              ran = true;
          }
      };
  }
  </code></pre>
  
  <p>I have tested the function like so:</p>
  
  <pre><code>function lazyLoadGrid(event, ui)
  {
      alert('hi');
  }
  
  var test1 = runOnce(lazyLoadGrid);
  var test2 = runOnce(lazyLoadGrid);
  
  test1();
  test2();
  
  test1();
  test2();
  </code></pre>
  
  <p>And it works as expected - 'hi' gets alerted exactly twice.</p>
  
  <p>But then I try to use runOnce(lazyLoadGrid) as the callback to a jQuery UI event:</p>
  
  <pre><code>$('.accordion').each(function() 
  { 
      $(this).accordion({ autoHeight: false, change: runOnce(lazyLoadGrid) });
  });
  </code></pre>
  
  <p>And madness ensues.  What I expect is that each 'accordion' on the page will run lazyLoadGrid() exactly once, when that accordion is first opened.  Instead, the closure callbacks seem to behave as if they are all referencing the same copy of 'ran'.  lazyLoadGrid() runs the first time I open any accordion, and then never runs again for any other accordion.  Logging the pre-condition value of 'ran' shows that it's 'true' every time I click any accordion after the first one.</p>
  
  <p>What is the explanation for this?  It may be worth noting I have an odd page, with nested accordions, and multiple jQuery UI tabs each containing accordions.  To make matters worse, when I switch tabs the closure actually does run on the first-opened accordion of any given tab.  Any advice is much appreciated.</p>