title: Formatting of JavaScript for MVC3 views
body: <p>I have tried many different ways to organize the JavaScript that is specific for each View now, but I have not found any way that I feel comfortable with. It seems messy anyway. Probably (and hopefully) that is because I haven't been working with JavaScript very long, and there is a good way of doing this.</p>
  
  <p>Currently what I'm doing is this:</p>
  
  <p>In my Layout file, I have the a RenderSection for scripts in addition to RenderBody. This section contains all JavaScript relevant for each single view. The global script is tucked away in it's own file.</p>
  
  <p>Inside this sections there is a lot of different part of JavaScript (for my biggest View currently there is about 600 lines of JavaScript):</p>
  
  <ul>
  <li>Some definitions of variables and setting different settings (jQuery settings among others).</li>
  <li>Hiding different DOM elements on the screen that will be made visible when the user interacts with the View later on.</li>
  <li>A lot of jQuery code for different events linked to DOM elements ( click/keyup++ )</li>
  <li>Some code refactored into methods because they are used by different jQuery events.</li>
  </ul>
  
  <p>The things I don't like here are mainly two things:</p>
  
  <ul>
  <li>All this code is put into one big codeblock and it's hard to find the parts of the script I'm looking for. Basically, it gets quite unmaintainable as the script grows.</li>
  <li>The script is located in the same file as the View. I would like to put the script into a seperate file, but I can't since I use different parts of my Model, and some HtmlHelpers inside the script as well. For example, where I execute some $.post calls, I use <code>@Url.Action('...')</code> to link it to the correct action method to be sure that my script will continue to work even if I change my routing.
  I also use the Model to decide if some elements should start out hidden or not like this (is this an ok way to make it start out hidden, or is there a better way? It seems kind of hacky even if I can't put my finger on it).:</li>
  </ul>
  
  <p><strong>code</strong></p>
  
  <pre><code>@if( Model.SomeBoolValue ){
    @:$("#DOMelementID").hide();
  }
  </code></pre>
  
  <p>Some pointers to get me in the right direction would be highly appreciated. I need to get this better structured before I lose control over my own code.</p>