title: .click() from an object property on appended buttons in jQuery
body: <p>I'm making several buttons from an object and append them to the only div in the body: #main, everything works fine except for actual click function: I can't seem to make the buttons alert different properties.</p>
  
  <p>This is my object:</p>
  
  <pre><code>var BrushDesc = function (n, i, t) {
      this.presetName = n;
      this.elemId = i;
      this.preset = t;
  };
  var brush = {};
  brush.circ = new BrushDesc("circle", "circle", "basic circle");
  brush.rect = new BrushDesc("rectangle", "rect", "19-2");
  brush.softy = new BrushDesc("round soft", "softy", "softy");
  brush.rake = new BrushDesc("|||", "rake", "21-3");
  </code></pre>
  
  <p>that was my first attempt appending the buttons but this always alerts last <code>.preset</code> property of the object:</p>
  
  <pre><code>for (var i in brush) {
      $('&lt;button id="'+brush[i].elemId+'"&gt;'+brush[i].presetName+'&lt;/button&gt;')
      .appendTo("#main")
      .click(function() {alert(brush[i].preset)}); 
  }
  </code></pre>
  
  <p>So I thought 'okay :('. Then I made it differently and this seems to work but in the same time this looks really wrong (mostly because this relies on <code>.elemId</code> and <code>brush.property</code> having the same name:</p>
  
  <pre><code>for (var i in brush) {
      $('&lt;button id="'+brush[i].elemId+'" class="main"&gt;'+brush[i].presetName+'&lt;/button&gt;')
      .appendTo("#main")
  }
  
  $(".main").click(function() {
      var buttonId = $(this).attr("id");
      for (var i in brush) {
          if (brush[i].elemId == buttonId) alert(brush[i].preset)
      }
  });
  </code></pre>
  
  <p>Can anyone please make it right?</p>
  
  <p><strong>edit:</strong> Thanks for pointing the Closures thread (haven't used them yet) Felix, but I'm not sure I understand how to apply this to my objects</p>
  
  <pre><code>var tps = [];
  function createTps(i) {return function() {alert(br[i].preset)}} //doh
  for (i = 0; i&lt;5; i++) {tps[i] = createTps(i)} //but I should have keys here, not numbers?
  
  var j = 0;
  for (var i in br) {
      $('&lt;button id="' + br[i].elemId + '" class="main"&gt;' + br[i].presetName + '&lt;/button&gt;')
      .appendTo("#main")
      .click(function() {tps[j](); j++}); //yeah, sure
  }
  </code></pre>
  
  <p><strong>edit2</strong> Actually a friend of mine suggested to use Immediately-Invoked Function Expression instead of closure and it worked perfectly</p>
  
  <pre><code>for (var i in brush) {
      (function (i) {
          $('&lt;button id="'+brush[i].elemId+'"&gt;'+brush[i].presetName+'&lt;/button&gt;')
          .appendTo("#main")
          .click(function() {alert(brush[i].preset)});
      })(i);
  }
  </code></pre>