title: CoffeeScript to attach objects to DOM
body: <p>I'm trying to implement application dialogs (modals) using CoffeeScript.</p>
  
  <p>The intent is you do some action which creates a CoffeeScript dialog object and attaches it to an array on the page so they can be referenced later (in case there are multiple).</p>
  
  <p>When some event such as clicking an overlay occurs, I want to hide the overlay but also any existing dialogs by destroying them.</p>
  
  <p>I am using jQuery for convenience as well.</p>
  
  <p>My desire is to learn how to use JavaScript/CoffeeScript objects to interact with the DOM instead of having a bunch of global events firing all over the place in one massive JS file.</p>
  
  <p>At the moment, when I call <code>dialog.destroy()</code> below, the console (using Chrome dev tools) states:</p>
  
  <p><code>Uncaught TypeError: dialog.destroy is not a function</code></p>
  
  <p>HTML page</p>
  
  <pre><code>&lt;a href="#" id="create-dialog-link"&gt;Link&lt;/a&gt;
  &lt;div id="overlay"&gt;&lt;/div&gt;
  </code></pre>
  
  <p>CoffeeScript global file</p>
  
  <pre><code>$("#create-dialog-link").on "click", -&gt;
    new Dialog("&lt;div class='dialog'&gt;content&lt;/div&gt;")
  
  $("#overlay").on "click", -&gt;
    this.hide() # Hide overlay
    dialog.destroy() for dialog in window.dialogs
  </code></pre>
  
  <p>CoffeeScript Dialog class</p>
  
  <pre><code>class @Dialog
    constructor: (element) -&gt;
      window.dialogs ||= [] # Initialize "global" array of dialogs
      @element = $(element) # Turn into jQuery object
      $("#overlay").show()
      @append_to_body()
  
    append_to_body: -&gt;
      $("body").append(@element) # Actually add HTML to DOM
      window.dialogs.push(@element) # Store array of dialogs
  
    destroy: -&gt;
      @element.remove() # Completely remove from DOM
  </code></pre>