title: Creating a Dynamic JSON array with callbacks (Inner Closure Issue)
body: <p>Very tough to title this thing.  I'm using a contextMenu plugin for jQuery.  </p>
  
  <p><a href="http://joewalnes.com/2011/07/22/a-simple-good-looking-context-menu-for-jquery/" rel="nofollow">http://joewalnes.com/2011/07/22/a-simple-good-looking-context-menu-for-jquery/</a></p>
  
  <p>It can take an array of items so I can dynamically create the menu based on a JSON object I have established previously called "packages" with is no more than an array of JSON objects containing an id and a title.  For example:</p>
  
  <pre><code>var packages = [{id:1,title:"One"},{id:2,title"Two"}];
  </code></pre>
  
  <p>As you might be able to tell from the example in the link I added, an "item" consists of, at minimum, a label and a callback function (which executes when the item is selected).  So my first thought was to do this:</p>
  
  <pre><code>var itemsArr = new Array();
  for(var i=0; i&lt;packages.length; i++)
  {
      itemsArr.push({label:packages[i].title, action:function(){myClickFunction(packages[i].id);}});
  }
  $("#myMenuThingie").contextPopup({title:"My Popup", items:itemsArr});
  </code></pre>
  
  <p>Now, I have verified that I can, infact pass an array to make this menu work properly.  The problem, I think, is the inner closure issue.  Because myClickFunction always gets the value of the last id, regardless of what gets clicked.  </p>
  
  <p>I found an article on "Immediately Invoked Function Expressions" here: <a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/" rel="nofollow">http://benalman.com/news/2010/11/immediately-invoked-function-expression/</a>, resulting in this modification: </p>
  
  <pre><code>for(var i=0; i&lt;packages.length; i++)
  {
      itemsArr.push({label:packages[i].title, action:(function(tempId){myClickFunction(tempId);})(packages[i].id)});
  }
  </code></pre>
  
  <p>however, that method won't really work either because it immediately invokes those functions, not on click.</p>
  
  <p>I am aware that I could try to use jQuery to find all the spans generated by the dropdown and apply click events that way, I'm just wondering if there is a way to create this array of objects with callbacks referencing the proper id.  I'll also take suggestions for other contextMenu plugins if it allows me to dynamically apply items in a similar fashion.</p>
  
  <p>Any thoughts?</p>