<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>ThoughtStream.new :derick_bailey</title>
	
	<link>http://lostechies.com/derickbailey</link>
	<description>Better Than Yesterday</description>
	<lastBuildDate>Thu, 09 Feb 2012 15:30:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/DerickBailey" /><feedburner:info uri="derickbailey" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><geo:lat>31.514067</geo:lat><geo:long>-97.235465</geo:long><creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license><image><link>http://creativecommons.org/licenses/by/3.0/</link><url>http://creativecommons.org/images/public/somerights20.gif</url><title>Some Rights Reserved</title></image><feedburner:emailServiceId>DerickBailey</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>Asynchronously Load HTML Templates For Backbone Views</title>
		<link>http://feedproxy.google.com/~r/DerickBailey/~3/BNfhhMjdorY/</link>
		<comments>http://lostechies.com/derickbailey/2012/02/09/asynchronously-load-html-templates-for-backbone-views/#comments</comments>
		<pubDate>Thu, 09 Feb 2012 15:30:47 +0000</pubDate>
		<dc:creator>Derick Bailey</dc:creator>
				<category><![CDATA[Async]]></category>
		<category><![CDATA[Backbone]]></category>
		<category><![CDATA[Backbone.Marionette]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Principles and Patterns]]></category>
		<category><![CDATA[User Experience]]></category>

		<guid isPermaLink="false">http://lostechies.com/derickbailey/?p=805</guid>
		<description>As JavaScript applications become larger and larger, we have to think about the download size, memory usage and other performance constraints for our end users. There are a number of aspects to consider, one of which is how to deliver&amp;#160;&amp;#8230; &lt;a href="http://lostechies.com/derickbailey/2012/02/09/asynchronously-load-html-templates-for-backbone-views/"&gt;Continue&amp;#160;reading&amp;#160;&lt;span class="meta-nav"&gt;&amp;#8594;&lt;/span&gt;&lt;/a&gt;</description>
			<content:encoded><![CDATA[<p>As JavaScript applications become larger and larger, we have to think about the download size, memory usage and other performance constraints for our end users. There are a number of aspects to consider, one of which is how to deliver the HTML templates that your application is using, to the user&#8217;s browser, so that your application can render the templates.</p>
<p>For my smaller applications, I tend to stuff a number of &lt;script&gt; blocks in to the HTML that the user downloads. This makes it easy for me to work with and I don&#8217;t have to worry about whether or not the template exists. But when the number of templates gets to be more than 5 or 6 small ones, this gets out of hand quickly. It makes it hard for me to manage them as I have to scroll through a lot of template code. Putting them in external files and then including them in the page with some server side technology helps the developer problem but it doesn&#8217;t solve the client problem of having to download all of these templates even if they are never used.</p>
<p>To deal with the issues surrounding templates in HTML files, we can split our templates in to separate files and then use asynchronous calls to our server to load them as needed.</p>
<h2>Backbone.View Render Semantics</h2>
<p>One of my goals, other than the asynchronous template loading, is to keep the general semantics of a Backbone View&#8217;s `render` method. It&#8217;s a short list, but it&#8217;s an important list as most of the Backbone community expects the render method to work this way.</p>
<p>Semantics are generally important as they give us information about how methods and objects are expected to be used, as well. This, in turn, informs the method signature and behavior. And all of this comes back to the <a href="http://code-magazine.com/article.aspx?quickid=1001061&amp;page=6">Liskov Substitution Principle (LSP)</a> from the <a href="http://code-magazine.com/Article.aspx?quickid=1001061">SOLID principles</a>, which tells us that we need to pay attention to semantics so that we can drop in replacements as needed.</p>
<p>The general semantics and method signature of a view&#8217;s render include:</p>
<ul>
<li><strong>No parameters</strong>: the render method shouldn&#8217;t require any parameters. You should be able to call `view.render()` and have it work fine</li>
<li><strong>Chainable</strong>: the render method should return `this` so that it can be chained with other method and attribute calls. This is most commonly done as `view.render().el` to grab the element that was rendered to</li>
<li><strong>Populate `el`, don&#8217;t replace it</strong>: the render method should populate a view&#8217;s `el` with any contents that the view needs to display. It generally shouldn&#8217;t replace the `el` as a whole</li>
</ul>
<p>Aside from these three items, there&#8217;s a lot of flexibility in how a view will typically be rendered. There&#8217;s also plenty of room for interpretation and divergence from this list. Many applications use a render method signature that takes parameters, or that replaces the `el` entirely. When changes like this are made, it&#8217;s a good idea to document them so that people will know why the changes are in place.</p>
<p>The benefit of keeping these semantics, though, is that you can swap out a synchronous, pre-loaded template rendering view with a view that uses an asynchronous template loading mechanism. Or, better yet, you can have an intelligent system that uses asynchronous calls to get the template the first time it needs it, and then uses caching to keep the template around and do synchronous rendering on subsequent requests for this view / template. If the semantics for the view are kept in place, it doesn&#8217;t matter how the view implements the rendering. The view can be dropped in or removed as needed, without having to change the surrounding code that uses it.</p>
<h2>Simple Async Template Retrieval</h2>
<p>We can keep this very simple, to begin with, using jQuery&#8217;s AJAX calls to load the template with a callback to do the actual rendering after the template is loaded.</p>
<div id="gist-1752642" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="nx">Backbone</span><span class="p">.</span><span class="nx">View</span><span class="p">.</span><span class="nx">extend</span><span class="p">({</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="nx">template</span><span class="o">:</span> <span class="s1">&#39;my-view-template&#39;</span><span class="p">,</span></div><div class='line' id='LC3'><br/></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="nx">render</span><span class="o">:</span> <span class="kd">function</span><span class="p">(){</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">that</span> <span class="o">=</span> <span class="k">this</span><span class="p">;</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">$</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="s2">&quot;/templates/&quot;</span> <span class="o">+</span> <span class="k">this</span><span class="p">.</span><span class="nx">template</span> <span class="o">+</span> <span class="s2">&quot;.html&quot;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">template</span><span class="p">){</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">html</span> <span class="o">=</span> <span class="nx">$</span><span class="p">(</span><span class="nx">template</span><span class="p">).</span><span class="nx">tmpl</span><span class="p">();</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">that</span><span class="p">.</span><span class="nx">$el</span><span class="p">.</span><span class="nx">html</span><span class="p">(</span><span class="nx">html</span><span class="p">);</span></div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">});</span></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="k">this</span><span class="p">;</span></div><div class='line' id='LC11'>&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC12'><br/></div><div class='line' id='LC13'><span class="p">});</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1752642/5c0cd33f99709a06d1ab876885942e3aa2c755fc/1.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1752642#file_1.js" style="float:right;margin-right:10px;color:#666">1.js</a>
            <a href="https://gist.github.com/1752642">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>In this example, we&#8217;re assuming that the view has a `template` attribute. This attribute represents the file that will be loaded from the server, and that file contain the actual template to be used.</p>
<p>We&#8217;re also using a convention of `/templates/{name}.html` for the template location on the server. This can be implemented easily in many different web server technologies. In Sinatra, for example, you can create a &#8220;public/templates&#8221; folder and put your HTML template files directly in that folder. They will be available without having to do anything more than start the Sinatra server.</p>
<p>When the call to `render` is made, the code makes an AJAX call back to the server to retrieve the specified template. A callback method is provided &#8211; and at this point, it assumes a successful call to get the template. When the template is returned from the server, the callback is fired, and the standard render code (using jQuery templates in this example) is executed.</p>
<p>Note that the `el` for the view is populated inside of the callback, but we are still calling `return this` at the end of the function. Even if we chain access to the `el` from the `render` method and immediately add the el&#8217;s contents to the DOM, this will still work:</p>
<blockquote>
<p>$(&#8220;#content&#8221;).html(view.render().el);</p>
</blockquote>
<p>The reason this works is that we are only populating the `el` with contents. We are not replacing it. When the AJAX call finally returns with the template, rendering it and populating the `el` will show the contents immediately because we&#8217;re setting the `html` method of an HTML element that is already attached to the DOM. It&#8217;s as if we had called `$(&#8220;#content&#8221;).html(&#8220;&lt;div&gt;some html&lt;/div&gt;&#8221;);` directly.</p>
<h2>Caching Templates</h2>
<p>Now that we have a template loading asynchronously, it would be nice to only load it once instead of every time it needs to be used. This will improve the overall performance of the application, from the user&#8217;s perspective.</p>
<p>To do this, we&#8217;ll need a little more than just some code in the render method. We want to re-use templates that we&#8217;ve already loaded, which means we can&#8217;t just store the template on the view instance. We need to store it in a place where any view instance can grab a copy of the template if it exists, or have an asynchronous call back to the server done to get the template when needed.</p>
<div id="gist-1752642" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="nx">TemplateManager</span> <span class="o">=</span> <span class="p">{</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="nx">templates</span><span class="o">:</span> <span class="p">{},</span></div><div class='line' id='LC3'><br/></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="nx">get</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">id</span><span class="p">,</span> <span class="nx">callback</span><span class="p">){</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">template</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">templates</span><span class="p">[</span><span class="nx">id</span><span class="p">];</span></div><div class='line' id='LC6'><br/></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">if</span> <span class="p">(</span><span class="nx">template</span><span class="p">)</span> <span class="p">{</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">callback</span><span class="p">(</span><span class="nx">template</span><span class="p">);</span></div><div class='line' id='LC9'><br/></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span> <span class="k">else</span> <span class="p">{</span></div><div class='line' id='LC11'><br/></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">that</span> <span class="o">=</span> <span class="k">this</span><span class="p">;</span></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">$</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="s2">&quot;/templates/&quot;</span> <span class="o">+</span> <span class="nx">id</span> <span class="o">+</span> <span class="s2">&quot;.html&quot;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">template</span><span class="p">){</span></div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">$tmpl</span> <span class="o">=</span> <span class="nx">$</span><span class="p">(</span><span class="nx">template</span><span class="p">);</span></div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">that</span><span class="p">.</span><span class="nx">templates</span><span class="p">[</span><span class="nx">id</span><span class="p">]</span> <span class="o">=</span> <span class="nx">$tmpl</span><span class="p">;</span></div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">callback</span><span class="p">(</span><span class="nx">$tmpl</span><span class="p">);</span></div><div class='line' id='LC17'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC18'><br/></div><div class='line' id='LC19'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC20'><br/></div><div class='line' id='LC21'>&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC22'><br/></div><div class='line' id='LC23'><span class="p">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1752642/437cd514b61f68c734b64faa38cebcb9ba3a8f48/2.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1752642#file_2.js" style="float:right;margin-right:10px;color:#666">2.js</a>
            <a href="https://gist.github.com/1752642">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>The template manager object has one primary method that we call: `get`. This method takes in a template name to be loaded and a callback method that is executed when the template is found. By using a callback method instead of returning a value directly, we can ensure both synchronous and asynchronous calls will work correctly.</p>
<p>When you call `get`, it will check a hash / object literal to see if the template you want is already loaded using the template name that you provide to make this check. If it exists, it executes the callback immediately and passes the template along. If it does not exist yet, an AJAX call is made with jQuery to get the template from the server. Once the template is loaded, the callback that you passed in will be executed and the template is passed to it.</p>
<p>We can now update our view to use the template manager:</p>
<div id="gist-1752642" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="nx">Backbone</span><span class="p">.</span><span class="nx">View</span><span class="p">.</span><span class="nx">extend</span><span class="p">({</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="nx">template</span><span class="o">:</span> <span class="s1">&#39;my-view-template&#39;</span><span class="p">,</span></div><div class='line' id='LC3'><br/></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="nx">render</span><span class="o">:</span> <span class="kd">function</span><span class="p">(){</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">that</span> <span class="o">=</span> <span class="k">this</span><span class="p">;</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">TemplateManager</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">template</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">template</span><span class="p">){</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">html</span> <span class="o">=</span> <span class="nx">$</span><span class="p">(</span><span class="nx">template</span><span class="p">).</span><span class="nx">tmpl</span><span class="p">();</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">that</span><span class="p">.</span><span class="nx">$el</span><span class="p">.</span><span class="nx">html</span><span class="p">(</span><span class="nx">html</span><span class="p">);</span></div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">});</span></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="k">this</span><span class="p">;</span></div><div class='line' id='LC11'>&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC12'><br/></div><div class='line' id='LC13'><span class="p">});</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1752642/e7c6dd25bacf6d8ea48046aa83a1ad13f1ecbfc4/3.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1752642#file_3.js" style="float:right;margin-right:10px;color:#666">3.js</a>
            <a href="https://gist.github.com/1752642">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>This isn&#8217;t much of a change from the view&#8217;s perspective. It&#8217;s better encapsulated, though, and a little easier to read. The real work is now being done in the TemplateManager object and we can change how it behaves as needed without having to update our views.</p>
<h2>Beyond Simple Caching</h2>
<p>There&#8217;s one remaining problem that this code has. If you have multiple instances of a view requesting the same template at roughly the same time, multiple AJAX calls will be made &#8211; one for each instance of the view. The net result is a slowdown in the application&#8217;s performance from too many network calls, and also a visual oddity where the views will appear one at a time as the AJAX calls finish. This can be a pretty big drag on performance and UI responsiveness.</p>
<p>Thanks to some previous digging in to jQuery&#8217;s deferred and some help from Steve Flitcroft (<a href="https://twitter.com/#!/red_square">@red_square</a>), I was able to solve this problem fairly easily. I put <a href="https://github.com/derickbailey/bbclonemail/blob/master/public/javascripts/bbclonemail.views.js#L28-52">the following code</a> in to my BBCloneMail app, which uses my <a href="https://github.com/derickbailey/backbone.marionette">Backbone.Marionette</a> plugin. It&#8217;s not directly implemented in Marionette&#8217;s `TemplateManager` but most of what you need is already there. There&#8217;s only a few additional lines of code that you need to make this work.</p>
<div id="gist-1752642" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="p">(</span><span class="kd">function</span><span class="p">(){</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">promises</span> <span class="o">=</span> <span class="p">{};</span></div><div class='line' id='LC3'><br/></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="c1">// Cache the returned deferred/promise by the id of the template</span></div><div class='line' id='LC5'>&nbsp;&nbsp;<span class="c1">// so that we can prevent multiple requests for the same template</span></div><div class='line' id='LC6'>&nbsp;&nbsp;<span class="c1">// from making the ajax call.</span></div><div class='line' id='LC7'>&nbsp;&nbsp;<span class="c1">//</span></div><div class='line' id='LC8'>&nbsp;&nbsp;<span class="c1">// This code is only safe to run synchronously. There exists a</span></div><div class='line' id='LC9'>&nbsp;&nbsp;<span class="c1">// race condition in this function, when run asynchronously,</span></div><div class='line' id='LC10'>&nbsp;&nbsp;<span class="c1">// which would nullify the benefit under certain circumstances.</span></div><div class='line' id='LC11'>&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">loadTemplateAsync</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">tmpId</span><span class="p">){</span></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">promise</span> <span class="o">=</span> <span class="nx">promises</span><span class="p">[</span><span class="nx">tmpId</span><span class="p">]</span> <span class="o">||</span> <span class="nx">$</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="s2">&quot;/templates/&quot;</span> <span class="o">+</span> <span class="nx">tmpId</span> <span class="o">+</span> <span class="s2">&quot;.html&quot;</span><span class="p">);</span></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">promises</span><span class="p">[</span><span class="nx">tmpId</span><span class="p">]</span> <span class="o">=</span> <span class="nx">promise</span><span class="p">;</span></div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="nx">promise</span><span class="p">;</span></div><div class='line' id='LC15'>&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC16'><br/></div><div class='line' id='LC17'>&nbsp;&nbsp;<span class="c1">// Use jQuery to asynchronously load the template. </span></div><div class='line' id='LC18'>&nbsp;&nbsp;<span class="nx">Backbone</span><span class="p">.</span><span class="nx">Marionette</span><span class="p">.</span><span class="nx">TemplateManager</span><span class="p">.</span><span class="nx">loadTemplate</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">templateId</span><span class="p">,</span> <span class="nx">callback</span><span class="p">){</span></div><div class='line' id='LC19'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">tmpId</span> <span class="o">=</span> <span class="nx">templateId</span><span class="p">.</span><span class="nx">replace</span><span class="p">(</span><span class="s2">&quot;#&quot;</span><span class="p">,</span> <span class="s2">&quot;&quot;</span><span class="p">);</span></div><div class='line' id='LC20'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">promise</span> <span class="o">=</span> <span class="nx">loadTemplateAsync</span><span class="p">(</span><span class="nx">tmpId</span><span class="p">);</span></div><div class='line' id='LC21'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">promise</span><span class="p">.</span><span class="nx">done</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">template</span><span class="p">){</span></div><div class='line' id='LC22'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">callback</span><span class="p">.</span><span class="nx">call</span><span class="p">(</span><span class="k">this</span><span class="p">,</span> <span class="nx">$</span><span class="p">(</span><span class="nx">template</span><span class="p">));</span></div><div class='line' id='LC23'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">});</span></div><div class='line' id='LC24'>&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC25'><span class="p">})();</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1752642/5d5796e3335c80182324ce00ca9263f371f6c265/5.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1752642#file_5.js" style="float:right;margin-right:10px;color:#666">5.js</a>
            <a href="https://gist.github.com/1752642">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>The basic idea is that I&#8217;m using a jQuery deferred / promise to fire the callback method from the loadTemplate parameters. To prevent multiple requests for the same template heading back to the server, I&#8217;m caching the promises by the template id. When a call to loadTemplate is made through the template manager, I check to see if I have a promise for that template already. If I do, I register the loadTemplate&#8217;s callback parameter with the promise. If I don&#8217;t, I create the promise and then store it by the template&#8217;s Id. Either way, I register the callback with the promise which <a href="http://lostechies.com/derickbailey/2012/02/07/rewriting-my-guaranteed-callbacks-code-with-jquery-deferred/">guarantees it will be executed</a>. Once the template is returned from the server and the promise is fulfilled (resolved), all of the callbacks are fired off with the template data and everything renders correctly.</p>
<p>Note, though, that this code is not 100% safe. If you call the template manager from code that is already asynchronous, you can end up with a race condition where multiple promises are created and multiple calls to get the template are done. You&#8217;ll still get all of your views rendered just fine, but this will eliminate the benefit of using a promise to reduce network calls. Calling this code synchronously, though, won&#8217;t cause this race condition and the templates will only load once before they are cached and re-used.</p>
<p><span style="font-size: 18px; font-weight: bold;">See It In Action</span></p>
<p>If you&#8217;d like to see an example of this code in action (including the deferred/promise code from above), check out my <a href="http://bbclonemail.heroku.com/">BBCloneMail</a> application and <a href="https://github.com/derickbailey/bbclonemail">it&#8217;s source code</a>. You&#8217;ll see the update to the TemplateManager&#8217;s `loadTemplate` function in the code. When you view the live site, switch to the Contacts view and refresh the page. There will be a small delay in the template loading, and then all of the contacts (which all individually requested the same contact template) will all display at once. Subsequent requests to those areas of the app will be cached, of course, improving the user experience and performance even more.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DerickBailey?a=BNfhhMjdorY:UJLvyF_u2B4:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=BNfhhMjdorY:UJLvyF_u2B4:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=BNfhhMjdorY:UJLvyF_u2B4:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=BNfhhMjdorY:UJLvyF_u2B4:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=BNfhhMjdorY:UJLvyF_u2B4:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=BNfhhMjdorY:UJLvyF_u2B4:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=I9og5sOYxJI" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=BNfhhMjdorY:UJLvyF_u2B4:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=BNfhhMjdorY:UJLvyF_u2B4:bcOpcFrp8Mo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=bcOpcFrp8Mo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DerickBailey/~4/BNfhhMjdorY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/derickbailey/2012/02/09/asynchronously-load-html-templates-for-backbone-views/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://lostechies.com/derickbailey/2012/02/09/asynchronously-load-html-templates-for-backbone-views/</feedburner:origLink></item>
		<item>
		<title>Rewriting My ‘Guaranteed Callbacks’ Code With jQuery Deferred</title>
		<link>http://feedproxy.google.com/~r/DerickBailey/~3/enxgwOKoqew/</link>
		<comments>http://lostechies.com/derickbailey/2012/02/07/rewriting-my-guaranteed-callbacks-code-with-jquery-deferred/#comments</comments>
		<pubDate>Tue, 07 Feb 2012 16:11:33 +0000</pubDate>
		<dc:creator>Derick Bailey</dc:creator>
				<category><![CDATA[Async]]></category>
		<category><![CDATA[Backbone]]></category>
		<category><![CDATA[Backbone.Marionette]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JQuery]]></category>

		<guid isPermaLink="false">http://lostechies.com/derickbailey/?p=809</guid>
		<description>In a previous post, I showed some code that I wrote to guarantee the execution of a callback method after a Backbone collection was loaded. Even if you added the callback after the collection had been loaded, it would run. Shortly&amp;#160;&amp;#8230; &lt;a href="http://lostechies.com/derickbailey/2012/02/07/rewriting-my-guaranteed-callbacks-code-with-jquery-deferred/"&gt;Continue&amp;#160;reading&amp;#160;&lt;span class="meta-nav"&gt;&amp;#8594;&lt;/span&gt;&lt;/a&gt;</description>
			<content:encoded><![CDATA[<p>In a previous post, I showed some code that I wrote to <a href="http://lostechies.com/derickbailey/2012/02/03/get-a-model-from-a-backbone-collection-without-knowing-if-the-collection-is-loaded/">guarantee the execution of a callback method</a> after a Backbone collection was loaded. Even if you added the callback after the collection had been loaded, it would run. Shortly after writing that blog post, I extracted the code in to my <a href="https://github.com/derickbailey/backbone.marionette">Backbone.Marionette</a> framework as an object called &#8220;Callbacks&#8221;. It worked and it got the job done, but I knew it could be done better.</p>
<p>Then a few of my friends started talking about <a href="http://api.jquery.com/category/deferred-object/">jQuery&#8217;s &#8220;deferred&#8221; objects and &#8220;promises&#8221;</a>. I had heard of this previously but had not bothered to learn it. When I finally decided to dig in to it, this morning, I found that it was a much more robust implementation of what I had just written. I found <a href="http://www.erichynds.com/jquery/using-deferreds-in-jquery/">a good article that helped me understand it better</a>, and began working on an update for Marionette to use deferred objects instead of my own code. Addy Osmani also wrote <a href="http://msdn.microsoft.com/en-us/scriptjunkie/gg723713">a really good article on MSDN</a>, which sheds even more light on how these work and how to work with them.</p>
<h2>My New &#8220;Callbacks&#8221; Object</h2>
<p>Here&#8217;s the end result of my digging in to this and replacing my Callbacks object with a jQuery deferred / promise implementation:</p>
<div id="gist-1760312" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="c1">// Callbacks</span></div><div class='line' id='LC2'><span class="c1">// ---------</span></div><div class='line' id='LC3'><br/></div><div class='line' id='LC4'><span class="c1">// A simple way of managing a collection of callbacks</span></div><div class='line' id='LC5'><span class="c1">// and executing them at a later point in time, using jQuery&#39;s</span></div><div class='line' id='LC6'><span class="c1">// `Deferred` object.</span></div><div class='line' id='LC7'><span class="nx">Marionette</span><span class="p">.</span><span class="nx">Callbacks</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(){</span></div><div class='line' id='LC8'>&nbsp;&nbsp;<span class="k">this</span><span class="p">.</span><span class="nx">deferred</span> <span class="o">=</span> <span class="nx">$</span><span class="p">.</span><span class="nx">Deferred</span><span class="p">();</span></div><div class='line' id='LC9'>&nbsp;&nbsp;<span class="k">this</span><span class="p">.</span><span class="nx">promise</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">deferred</span><span class="p">.</span><span class="nx">promise</span><span class="p">();</span></div><div class='line' id='LC10'><span class="p">};</span></div><div class='line' id='LC11'><br/></div><div class='line' id='LC12'><span class="nx">_</span><span class="p">.</span><span class="nx">extend</span><span class="p">(</span><span class="nx">Marionette</span><span class="p">.</span><span class="nx">Callbacks</span><span class="p">.</span><span class="nx">prototype</span><span class="p">,</span> <span class="p">{</span></div><div class='line' id='LC13'>&nbsp;&nbsp;</div><div class='line' id='LC14'>&nbsp;&nbsp;<span class="c1">// Add a callback to be executed. Callbacks added here are</span></div><div class='line' id='LC15'>&nbsp;&nbsp;<span class="c1">// guaranteed to execute, even if they are added after the </span></div><div class='line' id='LC16'>&nbsp;&nbsp;<span class="c1">// `run` method is called.</span></div><div class='line' id='LC17'>&nbsp;&nbsp;<span class="nx">add</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">callback</span><span class="p">){</span></div><div class='line' id='LC18'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">this</span><span class="p">.</span><span class="nx">promise</span><span class="p">.</span><span class="nx">done</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">context</span><span class="p">,</span> <span class="nx">options</span><span class="p">){</span></div><div class='line' id='LC19'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">callback</span><span class="p">.</span><span class="nx">call</span><span class="p">(</span><span class="nx">context</span><span class="p">,</span> <span class="nx">options</span><span class="p">);</span></div><div class='line' id='LC20'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">});</span></div><div class='line' id='LC21'>&nbsp;&nbsp;<span class="p">},</span></div><div class='line' id='LC22'><br/></div><div class='line' id='LC23'>&nbsp;&nbsp;<span class="c1">// Run all registered callbacks with the context specified. </span></div><div class='line' id='LC24'>&nbsp;&nbsp;<span class="c1">// Additional callbacks can be added after this has been run </span></div><div class='line' id='LC25'>&nbsp;&nbsp;<span class="c1">// and they will still be executed.</span></div><div class='line' id='LC26'>&nbsp;&nbsp;<span class="nx">run</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">context</span><span class="p">,</span> <span class="nx">options</span><span class="p">){</span></div><div class='line' id='LC27'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">this</span><span class="p">.</span><span class="nx">deferred</span><span class="p">.</span><span class="nx">resolve</span><span class="p">(</span><span class="nx">context</span><span class="p">,</span> <span class="nx">options</span><span class="p">);</span></div><div class='line' id='LC28'>&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC29'><span class="p">});</span></div><div class='line' id='LC30'><br/></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1760312/d3a94a8d1f93f70a76dd8f05fc9768c9618ec8a7/1.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1760312#file_1.js" style="float:right;margin-right:10px;color:#666">1.js</a>
            <a href="https://gist.github.com/1760312">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>This is a reduction in code and complexity, by about 75% on both counts.</p>
<h2>Things To Note</h2>
<p>Backbone.Marionette.Callbacks is a constructor function and you are expected to instantiate it before using it:</p>
<blockquote>
<p>var callbacks = new Backbone.Marionette.Callbacks();</p>
<p>callbacks.add(function(){ … });</p>
</blockquote>
<p>I&#8217;m using a single deferred object and promise object in this code. That&#8217;s done on purpose. I am collection an arbitrary list of callbacks, at an unknown time, and want to guarantee execution of those callbacks. By limiting this code to a single deferred object and a single promise, I can do exactly that.</p>
<p>When you call `add`, it sets up a `done` callback using the single promise object. No matter how many times you call `add`, it uses the same promise for that instance of Callbacks.</p>
<p>Then when you finally call `run`, it resolves the deferred object. Calling `resolve` on the deferred object will kick off all of the callback methods that I had set up with the when/then code.</p>
<p>After you call `run` and resolve the deferred object, you can still add callback functions to this Callbacks instance. When you do add more, jQuery is smart enough to know that the promise has already been fulfilled and it immediately executes the callback that you registered.</p>
<h2>Specs And Usage</h2>
<p>If you&#8217;d like to see the specs for this to show how it works with pre-run registered and post-run registered callback methods, you can grab the source code for <a href="https://github.com/derickbailey/backbone.marionette">Backbone.Marionette</a> and look at <a href="https://github.com/derickbailey/backbone.marionette/blob/master/spec/javascripts/callbacks.spec.js">the Jasmine specs for Callbacks</a>.</p>
<p>I&#8217;m using this Callbacks object in <a href="https://github.com/derickbailey/backbone.marionette/blob/master/backbone.marionette.js#L414-423">Marionette.Application&#8217;s &#8220;addInitializer&#8221; function</a>, which I&#8217;m using to guarantee initializer callback execution. Once I get back to working on the client project that I wrote that original code for, I&#8217;ll also update it to use the new Callbacks implementation instead of my original implementation, too.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DerickBailey?a=enxgwOKoqew:M9meUCLl0L4:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=enxgwOKoqew:M9meUCLl0L4:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=enxgwOKoqew:M9meUCLl0L4:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=enxgwOKoqew:M9meUCLl0L4:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=enxgwOKoqew:M9meUCLl0L4:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=enxgwOKoqew:M9meUCLl0L4:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=I9og5sOYxJI" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=enxgwOKoqew:M9meUCLl0L4:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=enxgwOKoqew:M9meUCLl0L4:bcOpcFrp8Mo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=bcOpcFrp8Mo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DerickBailey/~4/enxgwOKoqew" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/derickbailey/2012/02/07/rewriting-my-guaranteed-callbacks-code-with-jquery-deferred/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://lostechies.com/derickbailey/2012/02/07/rewriting-my-guaranteed-callbacks-code-with-jquery-deferred/</feedburner:origLink></item>
		<item>
		<title>3 Stages Of A Backbone Application’s Startup</title>
		<link>http://feedproxy.google.com/~r/DerickBailey/~3/d8eSj1rOt_8/</link>
		<comments>http://lostechies.com/derickbailey/2012/02/06/3-stages-of-a-backbone-applications-startup/#comments</comments>
		<pubDate>Mon, 06 Feb 2012 13:30:12 +0000</pubDate>
		<dc:creator>Derick Bailey</dc:creator>
				<category><![CDATA[Backbone]]></category>
		<category><![CDATA[Backbone.Marionette]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Semantics]]></category>

		<guid isPermaLink="false">http://lostechies.com/derickbailey/?p=803</guid>
		<description>Most Backbone application examples that you find on the web are very small and very simple. They tend to use a very simple idea of an application &amp;#8220;init&amp;#8221; method to start up a router and have the router kick off&amp;#160;&amp;#8230; &lt;a href="http://lostechies.com/derickbailey/2012/02/06/3-stages-of-a-backbone-applications-startup/"&gt;Continue&amp;#160;reading&amp;#160;&lt;span class="meta-nav"&gt;&amp;#8594;&lt;/span&gt;&lt;/a&gt;</description>
			<content:encoded><![CDATA[<p>Most Backbone application examples that you find on the web are very small and very simple. They tend to use a very simple idea of an application &#8220;init&#8221; method to start up a router and have the router kick off the real application code. I find this path to be very constraining, though. For the most basic of applications it works perfectly fine, but when you get in to anything of any real size and complexity, it becomes difficult to work with.</p>
<p>My Backbone.Marionette add-on helps to alleviate this problem by introducing the idea of application initializer callbacks. I&#8217;ve talked about these before, and I use them quite extensively in my applications. It really helps to keep my code clean and separated. And I recently realized that there&#8217;s an unintended benefit to using initializers like this: explicitly identifying the different stages of starting an application.</p>
<h2>The 3 Stages</h2>
<p>The three stages that I have identified in my own applications are (in order):</p>
<ol>
<li>The Application&#8217;s Foundation</li>
<li>The Application&#8217;s Initialization</li>
<li>A Contextual Start (optional)</li>
</ol>
<p>Honestly, I could break this down in to a significantly larger number of stages if I really wanted to get fine-grained and detailed. More specifically, it&#8217;s the 2nd stage that can be broken down in to pre-initialization, initialization, and post-initialization. But I think as a general place to start, identifying 3 primary stages for an application&#8217;s startup is a good idea. It gives us a better understanding of what code should go where, helps us keep our code clean, improves re-usability and flexibility, and will likely help us scale our apps as well.</p>
<p><span style="font-size: 18px; font-weight: bold;">Stage 1: The Application&#8217;s Foundation</span></p>
<p>Consider this to be the stage where the browser is simply grabbing all of the specified resources from the server and running through the first pass of parsing the HTML, laying out what the static HTML has provided, styling it with the basic CSS definitions, displaying any images and text from the static HTML, and parsing the JavaScript files so it can get ready to run them. I&#8217;ve never seen an HTML application that didn&#8217;t have this stage in it, because without it, your browser doesn&#8217;t have anything to do or show.</p>
<p>This is the one step the everyone does, and does well.</p>
<h2>Stage 2: The Application&#8217;s Initialization</h2>
<p>Every application has an initialization stage. Some are more elaborate than others. At times you can get away with the over-simplified &#8220;app&#8221; object with an &#8220;init&#8221; method on it, like many of the sample apps and boilerplate codes will suggest:</p>
<div id="gist-1731648" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="nx">App</span> <span class="o">=</span> <span class="p">{</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="nx">init</span><span class="o">:</span> <span class="kd">function</span><span class="p">(){</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">// app initialization and startup goes here</span></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC5'><span class="p">}</span></div><div class='line' id='LC6'><br/></div><div class='line' id='LC7'><span class="nx">App</span><span class="p">.</span><span class="nx">init</span><span class="p">();</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1731648/5d7d6d280ce51e71ccf1f103954fad1a99e5b4b2/1.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1731648#file_1.js" style="float:right;margin-right:10px;color:#666">1.js</a>
            <a href="https://gist.github.com/1731648">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>But when you get in to an application of any significant size and complexity, the single &#8220;init&#8221; method becomes a junk drawer where you tend to throw code because you haven&#8217;t yet identified where it should belong. Using a series of small initializer functions for each area of your application will help to alleviate this problem, as I&#8217;ve mentioned before. But the real question is:</p>
<p>What goes in the initializers?</p>
<p>Initializers are the bits of code, functionality, data and display that are absolutely required for your app to do it&#8217;s job, no matter what part of the application the user is trying to load up and use. They are the bits that must be initialized before the user can do anything meaningful with your application.</p>
<p>If your app has a menu structure generated by Backbone code, and it must always be present in the application, this should be in an initializer. If you&#8217;re building a multi-room chat application and you need to list the rooms that the user has favorited in a small block on the screen that is always visible to the user, this should be an initializer. If you&#8217;re building an image gallery and you need to load a thumb-nail list of images to show, no matter which image the user is trying to view, this is an initializer.</p>
<p>Other parts of your application code that the user doesn&#8217;t directly see may also be contenders for initializers, too. For example, if you have a router that needs to be up and running, the router probably needs to be instantiated inside of an initializer. But &#8211; and this is an important but &#8211; the routes on that router should not be executed during initialization. Instantiate the router and wait until after initialization has completed to call the &#8220;Backbone.history.start()&#8221; method, kicking off your route handlers.</p>
<h2>Stage 3: A Contextual Start (optional)</h2>
<p>I call this stage optional because not every application has a contextual kick off. Sometimes an application only needs initializers. The classic &#8220;todo&#8221; application is a great example of this. There is no contextual start up for this app. When the application is loaded, it initializes itself with the list of to do items and then it waits for the user to interact with the list.</p>
<p>When a Backbone application uses a router to respond to url pushState or hash fragment changes, though, it does have a contextual starting point. Each route that a user is allowed to bookmark or copy as a direct link will provide the context that our application needs to use, to get the user back to where they want to be. Even if a Backbone app has a router and contextual start, though, it may not be used. If there user hits the root of the application, there may not be any additional code to run for the empty (&#8220;&#8221;) route. When the user hits a route, though, that route must server up the context and application state that the user expects to see.</p>
<p>The problem that I see in most routed Backbone applications, though, is that they bundle the application initialization with the contextual start. That is, people tend to use the router and it&#8217;s callback methods as the sole place to get the application initialized <em>and</em> get the user back to the context of the route that they requested. For trivial applications, this may be fine. The initialization code may be so small that it doesn&#8217;t really matter if it&#8217;s crammed in to the router. But for any real application with any amount of complexity, this is a bad idea. It couples two very distinct parts of the application startup very tightly, and it can lead to bloated and unmaintainable routers with limited entry points in to the application.</p>
<p>So… what goes in the contextual start, other than just saying route callbacks?</p>
<p>Your route callbacks should be as simple as possible. They shouldn&#8217;t initialize your system as a whole. Rather, they should be used to determine the state of the application that the user wishes to see. Therefore, the code that goes in to a route callback should be the smallest amount of code that you can write, to get your application from it&#8217;s initial state (the state that it was in when the initializers completed) to the desired state.</p>
<p>In an image gallery application, a user may hit a bookmark that points to a specific image. For example, &#8220;#images/4&#8243;. The route callback that executes should load the requested image and display it on the screen:</p>
<div id="gist-1731648" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="nx">Backbone</span><span class="p">.</span><span class="nx">Router</span><span class="p">.</span><span class="nx">extend</span><span class="p">({</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="nx">routes</span><span class="o">:</span> <span class="p">{</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="s2">&quot;image/:id&quot;</span><span class="o">:</span> <span class="s2">&quot;imageById&quot;</span></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="p">},</span></div><div class='line' id='LC5'>&nbsp;</div><div class='line' id='LC6'>&nbsp;&nbsp;<span class="nx">imageById</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">id</span><span class="p">){</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">image</span> <span class="o">=</span> <span class="nx">imageCollection</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="nx">id</span><span class="p">);</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">App</span><span class="p">.</span><span class="nx">showImage</span><span class="p">(</span><span class="nx">image</span><span class="p">);</span></div><div class='line' id='LC9'>&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC10'><span class="p">});</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1731648/89de647c4000cb1aad368e7b9e58072e55b8b2b9/2.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1731648#file_2.js" style="float:right;margin-right:10px;color:#666">2.js</a>
            <a href="https://gist.github.com/1731648">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>In a multi-room chat application, a user may hit a bookmark that should take them directly in to a specific chat room. For example, &#8220;#backbone&#8221;. The route callback that executes should take this room name and call the code that is necessary to enter the chat room.</p>
<p>Chances are this is a fairly involved set of code. You&#8217;ll need to load the list of users in the chat room. You&#8217;ll need to clear the current chat windows and possibly pre-load recent messages to be displayed. You may also need to change a browser&#8217;s websocket event listeners to pick up events for this specific room instead, so that messages for this room can be displayed as they come in.</p>
<p>This is a lot of code to run, and it&#8217;s fare more code than should be allowed in a route callback method. It should, then, be encapsulated in an object that is responsible for registering the user as having entered that chat room. This object is then called from the router:</p>
<div id="gist-1731648" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="nx">Backbone</span><span class="p">.</span><span class="nx">Router</span><span class="p">.</span><span class="nx">extend</span><span class="p">({</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="nx">routes</span><span class="o">:</span> <span class="p">{</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="s2">&quot;:roomname&quot;</span><span class="o">:</span> <span class="s2">&quot;chatroom&quot;</span></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="p">},</span></div><div class='line' id='LC5'>&nbsp;</div><div class='line' id='LC6'>&nbsp;&nbsp;<span class="nx">chatroom</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">roomname</span><span class="p">){</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">ChatApp</span><span class="p">.</span><span class="nx">enterRoom</span><span class="p">(</span><span class="nx">roomname</span><span class="p">);</span></div><div class='line' id='LC8'>&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC9'><span class="p">});</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1731648/124f65b2e0709143308b84f18e4cc4c9e11d6adf/3.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1731648#file_3.js" style="float:right;margin-right:10px;color:#666">3.js</a>
            <a href="https://gist.github.com/1731648">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Furthermore, there&#8217;s a high likelihood that the user will be able to enter chat rooms using some interaction on the web page. They may click on a chat room name in their favorite&#8217;s list, or they may type in a command like &#8220;/join #backbone&#8221; in to the chat application&#8217;s command area. For any of the the multiple ways to enter a chatroom, the code that is executed should be the same. Having the route callback be as simple and stupid as possible will promote code re-use and allow these three options to be easily implemented. If you only need to call &#8220;ChatApp.enterRoom(&#8216;someRoom&#8217;)&#8221; to enter any room that the user specifies, providing options for how the user enters a room becomes trivial.</p>
<h2>Putting It All Together</h2>
<p>There are many different ways of stringing these different stages together. There are many different tools that help us to easily create the HTML that we need, include the CSS and JavaScript assets, and kick things off. Some applications are small enough that an initialization step and contextual start step can be combined. Most applications of any significant size, though, should think about separating these in to explicit steps in order to promote better architecture, clean code, and re-use of code.</p>
<p>For me, I&#8217;m accomplishing stages 2 and 3 with my Backbone.Marionette add-on. It provides a very clean way to create initializers:</p>
<div id="gist-1731648" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="nx">App</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Backbone</span><span class="p">.</span><span class="nx">Marionette</span><span class="p">.</span><span class="nx">Application</span><span class="p">();</span></div><div class='line' id='LC2'><br/></div><div class='line' id='LC3'><span class="nx">App</span><span class="p">.</span><span class="nx">addInitializer</span><span class="p">(</span><span class="kd">function</span><span class="p">(){</span></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="c1">// add some app initialization code, here</span></div><div class='line' id='LC5'><span class="p">});</span></div><div class='line' id='LC6'><br/></div><div class='line' id='LC7'><span class="nx">App</span><span class="p">.</span><span class="nx">addInitializer</span><span class="p">(</span><span class="kd">function</span><span class="p">(){</span></div><div class='line' id='LC8'>&nbsp;&nbsp;<span class="c1">// more initialization stuff </span></div><div class='line' id='LC9'>&nbsp;&nbsp;<span class="c1">// for a different part of the app</span></div><div class='line' id='LC10'><span class="p">});</span></div><div class='line' id='LC11'><br/></div><div class='line' id='LC12'><span class="c1">// run all the initializers and start the app</span></div><div class='line' id='LC13'><span class="nx">App</span><span class="p">.</span><span class="nx">start</span><span class="p">();</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1731648/bbd27a6654733f3d4ecfb49aadc29a536d5fbb8f/4.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1731648#file_4.js" style="float:right;margin-right:10px;color:#666">4.js</a>
            <a href="https://gist.github.com/1731648">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>At the time of this writing, though, I don&#8217;t have an explicit &#8220;startup&#8221; callback mechanism in place. I have a &#8220;start&#8221; method on my Marionette.Application object. But right now this really only fires up the initializer callbacks. So, I&#8217;m currently using the &#8220;initialize:after&#8221; event to run my start code. I see this as a problem, though &#8211; not of a technical nature, but of a semantic nature. And yes, semantics are important.</p>
<div id="gist-1731648" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="nx">App</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Backbone</span><span class="p">.</span><span class="nx">Marionette</span><span class="p">.</span><span class="nx">Application</span><span class="p">();</span></div><div class='line' id='LC2'><br/></div><div class='line' id='LC3'><span class="cm">/* ... initializers go here ... */</span></div><div class='line' id='LC4'><br/></div><div class='line' id='LC5'><span class="c1">// contextual startup</span></div><div class='line' id='LC6'><span class="nx">App</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s2">&quot;initialize:after&quot;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(){</span></div><div class='line' id='LC7'>&nbsp;&nbsp;<span class="nx">Backbone</span><span class="p">.</span><span class="nx">history</span><span class="p">.</span><span class="nx">start</span><span class="p">();</span></div><div class='line' id='LC8'><span class="p">});</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1731648/102becd9b2b776c4569830f2383ae625105885a2/5.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1731648#file_5.js" style="float:right;margin-right:10px;color:#666">5.js</a>
            <a href="https://gist.github.com/1731648">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>I&#8217;m not sure what the new implementation will look like, but it may end up being a &#8220;startup&#8221; callback method, similar to the initializer methods. The startup callback (or callbacks?) would execute after all of the initialization is done. This will provide a cleaner separation between the two concerns of initialization vs startup. I&#8217;ll have to see where this leads me, though, as right now, the majority of what I do for a contextual start is simply call &#8220;Backbone.history.start()&#8221;, as I showed in the above example.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DerickBailey?a=d8eSj1rOt_8:RsDjNC197bU:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=d8eSj1rOt_8:RsDjNC197bU:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=d8eSj1rOt_8:RsDjNC197bU:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=d8eSj1rOt_8:RsDjNC197bU:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=d8eSj1rOt_8:RsDjNC197bU:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=d8eSj1rOt_8:RsDjNC197bU:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=I9og5sOYxJI" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=d8eSj1rOt_8:RsDjNC197bU:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=d8eSj1rOt_8:RsDjNC197bU:bcOpcFrp8Mo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=bcOpcFrp8Mo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DerickBailey/~4/d8eSj1rOt_8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/derickbailey/2012/02/06/3-stages-of-a-backbone-applications-startup/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://lostechies.com/derickbailey/2012/02/06/3-stages-of-a-backbone-applications-startup/</feedburner:origLink></item>
		<item>
		<title>Get A Model From A Backbone Collection Without Knowing If The Collection Is Loaded</title>
		<link>http://feedproxy.google.com/~r/DerickBailey/~3/XeHBx3R6ztk/</link>
		<comments>http://lostechies.com/derickbailey/2012/02/03/get-a-model-from-a-backbone-collection-without-knowing-if-the-collection-is-loaded/#comments</comments>
		<pubDate>Fri, 03 Feb 2012 15:51:52 +0000</pubDate>
		<dc:creator>Derick Bailey</dc:creator>
				<category><![CDATA[Async]]></category>
		<category><![CDATA[Backbone]]></category>
		<category><![CDATA[Backbone.Marionette]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://lostechies.com/derickbailey/?p=799</guid>
		<description>In working with a client recently, we ran in to a rather sticky situation. We were setting up a route to &amp;#8220;persons/:id&amp;#8221;, and as you would expect, we wanted to load the person in question and display the details of&amp;#160;&amp;#8230; &lt;a href="http://lostechies.com/derickbailey/2012/02/03/get-a-model-from-a-backbone-collection-without-knowing-if-the-collection-is-loaded/"&gt;Continue&amp;#160;reading&amp;#160;&lt;span class="meta-nav"&gt;&amp;#8594;&lt;/span&gt;&lt;/a&gt;</description>
			<content:encoded><![CDATA[<p>In working with a client recently, we ran in to a rather sticky situation. We were setting up a route to &#8220;persons/:id&#8221;, and as you would expect, we wanted to load the person in question and display the details of that person. The trick, though, is that we needed to wait until the persons collection was loaded to be able to retrieve the person from the collection. If we navigate to this route from somewhere else in the application, this isn&#8217;t an issue. The persons collection was already loaded and everything goes on normally. If we use a bookmark to get to this url directly, though, then there was no guarantee that the persons collection was loaded because we had not previously run any code to load the collection.</p>
<p>Depending on how the application is architected, and when the persons collection is expected to be loaded, there are a few options that I can see for solving this problem.</p>
<p><span style="font-size: 18px; font-weight: bold;">Option: Fetch The Model From The Server</span></p>
<p>The most basic option, and probably the easiest to deal with, is just to fetch the model from the server based on the id parameter that you get from the route.</p>
<p>In this case you just need to create a new model instance, set the `id` attribute on the model directly and then call `.fetch` on the model. It will make the trip to the server to get the data. You can either listen to a &#8220;change&#8221; event on the model or provide a &#8220;success&#8221; callback in the fetch method, to know when the data has been returned so that you can load it in to your view and display it as needed.</p>
<div id="gist-1730803" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="nx">personById</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">id</span><span class="p">){</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">person</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Person</span><span class="p">();</span></div><div class='line' id='LC3'>&nbsp;&nbsp;<span class="nx">person</span><span class="p">.</span><span class="nx">id</span> <span class="o">=</span> <span class="nx">id</span><span class="p">;</span></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="nx">person</span><span class="p">.</span><span class="nx">fetch</span><span class="p">({</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">success</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">model</span><span class="p">,</span> <span class="nx">response</span><span class="p">){</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">App</span><span class="p">.</span><span class="nx">showPerson</span><span class="p">(</span><span class="nx">model</span><span class="p">);</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC8'>&nbsp;&nbsp;<span class="p">})</span></div><div class='line' id='LC9'><span class="p">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1730803/766ff0b3d93a3c2409d8f6d196581e8e1ec28477/1.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1730803#file_1.js" style="float:right;margin-right:10px;color:#666">1.js</a>
            <a href="https://gist.github.com/1730803">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>The major problem here is that you have not loaded the persons collection at all. If the persons collection is expected to be loaded because it&#8217;s being used for something related to displaying or working with the individual person model, then this option might not work for you. You could run some additional code to load the collection separately (asynchronously, since it works that way by default). This might help get around any potential issues of needing the collection.</p>
<h2>Option: Use The Collection&#8217;s &#8220;reset&#8221; Event</h2>
<p>Another easy option may be to load the collection when the request for the route is made. You would set up a new collection instance, bind a callback function to the collection&#8217;s &#8220;reset&#8221; event, and then call `.fetch` on the collection. The callback method would be responsible for retrieving the specific model from the collection and then creating and displaying the view.</p>
<div id="gist-1730803" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="nx">personById</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">id</span><span class="p">){</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">persons</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">PersonCollection</span><span class="p">();</span></div><div class='line' id='LC3'><br/></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="c1">// note that &quot;bind&quot; is now &quot;on&quot; in Backbone v0.9.x</span></div><div class='line' id='LC5'>&nbsp;&nbsp;<span class="nx">persons</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s2">&quot;reset&quot;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">collection</span><span class="p">,</span> <span class="nx">response</span><span class="p">){</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">person</span> <span class="o">=</span> <span class="nx">collection</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="nx">id</span><span class="p">);</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">App</span><span class="p">.</span><span class="nx">showPerson</span><span class="p">(</span><span class="nx">person</span><span class="p">);</span></div><div class='line' id='LC8'>&nbsp;&nbsp;<span class="p">});</span></div><div class='line' id='LC9'><br/></div><div class='line' id='LC10'>&nbsp;&nbsp;<span class="nx">persons</span><span class="p">.</span><span class="nx">fetch</span><span class="p">();</span></div><div class='line' id='LC11'><span class="p">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1730803/68fa47edcd14d5be22ff12f63298766a11d11970/2.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1730803#file_2.js" style="float:right;margin-right:10px;color:#666">2.js</a>
            <a href="https://gist.github.com/1730803">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>There are some potential issues with this solution, though. If you already have the persons collection loaded, then you&#8217;re going to load it a second time just to get the one model from it. To mitigate this problem, you would need two different entry points in to the display of the person: one for when you hit the route directly through a bookmark, and one for when the user is already in the app and navigates to the person display through other means.</p>
<p>Having two different entry points in to this part of the app may not be a bad idea. This largely depends on how the application is architected. You wouldn&#8217;t want to duplicate all of the code that sets up the display of the person&#8217;s details in both of the entry points, but you wouldn&#8217;t want to have a bunch of ugly if-statements in that code to determine how to set things up, either. Some simple abstractions of the common bits would help keep this code manageable.</p>
<h2>Option: Building An &#8220;onReset&#8221; Callback</h2>
<p><strong>UPDATE:</strong></p>
<p>FYI &#8211; I have an updated version of this code available in my <a href="https://github.com/derickbailey/backbone.marionette">Backbone.Marionette</a> plugin, as Backbone.Marionette.Callbacks. It <a href="http://lostechies.com/derickbailey/2012/02/07/rewriting-my-guaranteed-callbacks-code-with-jquery-deferred/">reduces the code and complexity significantly</a>, and also eliminates the race condition issues that I mention below. Be sure to use that Callbacks object instead of the code I&#8217;ve listed here.</p>
<p><strong>:END UPDATE</strong></p>
<p><strong><br /></strong></p>
<p>The third option that I can think of &#8211; and the one that I implemented for this particular client project &#8211; is a variation of using the collection&#8217;s reset event. The idea is to build an &#8220;onReset&#8221; callback system that is aware of whether or not the collection has already been loaded or is still waiting to be loaded.</p>
<p>If you have the persons collection being loaded from some other application initialization code, then you don&#8217;t necessarily have the ability to use a simple reset event as shown above. You could try to use the reset event, but there&#8217;s a race condition that is introduced in low-latency, high speed networks (i.e. your local development machine).</p>
<p>If you don&#8217;t control when the `.fetch` method is called, then you may end up binding to the reset event after the collection has already been reset. In that scenario &#8211; which is very likely to happen when working in a local development environment &#8211; your view for the specific person model will never get displayed.</p>
<p>The solution I came up with is to have a callback mechanism built in to the collection, that pays attention to the collection&#8217;s reset event and knows to either wait for the reset event to be fired, or to fire the callbacks immediately because the collection has already been loaded. I&#8217;m calling this an &#8220;onReset&#8221; callback, for lack of a better description at this point.</p>
<p>The code to use the onReset callbacks would look something like this:</p>
<div id="gist-1730803" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="c1">// App.js</span></div><div class='line' id='LC2'><span class="c1">// ------</span></div><div class='line' id='LC3'><span class="c1">// some initialization code that happens elsewhere, using Backbone.Marionette</span></div><div class='line' id='LC4'><br/></div><div class='line' id='LC5'><span class="nx">App</span><span class="p">.</span><span class="nx">addInitializer</span><span class="p">(</span><span class="kd">function</span><span class="p">(){</span></div><div class='line' id='LC6'>&nbsp;&nbsp;<span class="nx">App</span><span class="p">.</span><span class="nx">persons</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">PersonCollection</span><span class="p">();</span></div><div class='line' id='LC7'>&nbsp;&nbsp;<span class="nx">App</span><span class="p">.</span><span class="nx">persons</span><span class="p">.</span><span class="nx">fetch</span><span class="p">();</span></div><div class='line' id='LC8'><span class="p">});</span></div><div class='line' id='LC9'><br/></div><div class='line' id='LC10'><br/></div><div class='line' id='LC11'><br/></div><div class='line' id='LC12'><span class="c1">// PersonRouter.js</span></div><div class='line' id='LC13'><span class="c1">// ---------------</span></div><div class='line' id='LC14'><span class="c1">// The router callback that needs to get the person</span></div><div class='line' id='LC15'><br/></div><div class='line' id='LC16'><span class="nx">personById</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">id</span><span class="p">){</span></div><div class='line' id='LC17'>&nbsp;&nbsp;<span class="nx">App</span><span class="p">.</span><span class="nx">persons</span><span class="p">.</span><span class="nx">onReset</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">collection</span><span class="p">){</span></div><div class='line' id='LC18'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">person</span> <span class="o">=</span> <span class="nx">collection</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="nx">id</span><span class="p">);</span></div><div class='line' id='LC19'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">App</span><span class="p">.</span><span class="nx">showPerson</span><span class="p">(</span><span class="nx">person</span><span class="p">);</span></div><div class='line' id='LC20'>&nbsp;&nbsp;<span class="p">});</span></div><div class='line' id='LC21'><span class="p">}</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1730803/956ae14990497446c30ffb762d3c903461698df3/3.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1730803#file_3.js" style="float:right;margin-right:10px;color:#666">3.js</a>
            <a href="https://gist.github.com/1730803">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>In this setup, adding an onReset callback guarantees the callback&#8217;s execution. If the collection has not yet been loaded, then it stores the callback and waits for the reset event to fire. If the reset event has already been fired, then it simply executes the callback immediately. Either way, your callback will be executed and you will have the collection available when it does.</p>
<h2>Race Condition Reduced. Eliminated?</h2>
<p>Here&#8217;s the implementation for the onReset code. It&#8217;s generally functional and I haven&#8217;t yet run in to any problems, yet.</p>
<div id="gist-1730803" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="nx">OnResetCollection</span> <span class="o">=</span> <span class="nx">Backbone</span><span class="p">.</span><span class="nx">Collection</span><span class="p">.</span><span class="nx">extend</span><span class="p">({</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="nx">constructor</span><span class="o">:</span> <span class="kd">function</span><span class="p">(){</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">args</span> <span class="o">=</span> <span class="nx">slice</span><span class="p">(</span><span class="nx">arguments</span><span class="p">);</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">Backbone</span><span class="p">.</span><span class="nx">Collection</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">constructor</span><span class="p">.</span><span class="nx">apply</span><span class="p">(</span><span class="k">this</span><span class="p">,</span> <span class="nx">args</span><span class="p">);</span></div><div class='line' id='LC5'><br/></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">this</span><span class="p">.</span><span class="nx">onResetCallbacks</span> <span class="o">=</span> <span class="p">[];</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">this</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s2">&quot;reset&quot;</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">collectionReset</span><span class="p">,</span> <span class="k">this</span><span class="p">);</span></div><div class='line' id='LC8'>&nbsp;&nbsp;<span class="p">},</span></div><div class='line' id='LC9'><br/></div><div class='line' id='LC10'>&nbsp;&nbsp;<span class="nx">onReset</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">callback</span><span class="p">){</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">this</span><span class="p">.</span><span class="nx">onResetCallbacks</span><span class="p">.</span><span class="nx">push</span><span class="p">(</span><span class="nx">callback</span><span class="p">);</span></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">this</span><span class="p">.</span><span class="nx">collectionLoaded</span> <span class="o">&amp;&amp;</span> <span class="k">this</span><span class="p">.</span><span class="nx">fireResetCallbacks</span><span class="p">();</span></div><div class='line' id='LC13'>&nbsp;&nbsp;<span class="p">},</span></div><div class='line' id='LC14'><br/></div><div class='line' id='LC15'>&nbsp;&nbsp;<span class="nx">collectionReset</span><span class="o">:</span> <span class="kd">function</span><span class="p">(){</span></div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="k">this</span><span class="p">.</span><span class="nx">collectionLoaded</span><span class="p">)</span> <span class="p">{</span></div><div class='line' id='LC17'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">this</span><span class="p">.</span><span class="nx">collectionLoaded</span> <span class="o">=</span> <span class="kc">true</span></div><div class='line' id='LC18'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC19'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">this</span><span class="p">.</span><span class="nx">fireResetCallbacks</span><span class="p">();</span></div><div class='line' id='LC20'>&nbsp;&nbsp;<span class="p">},</span></div><div class='line' id='LC21'><br/></div><div class='line' id='LC22'>&nbsp;&nbsp;<span class="nx">fireResetCallbacks</span><span class="o">:</span> <span class="kd">function</span><span class="p">(){</span></div><div class='line' id='LC23'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">callback</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">onResetCallbacks</span><span class="p">.</span><span class="nx">pop</span><span class="p">();</span></div><div class='line' id='LC24'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">if</span> <span class="p">(</span><span class="nx">callback</span><span class="p">){</span></div><div class='line' id='LC25'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">callback</span><span class="p">(</span><span class="k">this</span><span class="p">);</span></div><div class='line' id='LC26'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">this</span><span class="p">.</span><span class="nx">fireResetCallbacks</span><span class="p">();</span></div><div class='line' id='LC27'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC28'>&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC29'><span class="p">});</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1730803/8507df0b66d1788cf02245b8fd2bb05fcd4e8df5/4.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1730803#file_4.js" style="float:right;margin-right:10px;color:#666">4.js</a>
            <a href="https://gist.github.com/1730803">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>You can then extend from OnResetCollection instead of Backbone.Collection to get this functionality.</p>
<p>I still worry that there&#8217;s a potential race condition in between the logic and the pop&#8217;ing of items off the array. I&#8217;ve travelled every logical path of execution for the asynchronous call and onReset call that I can think of, and I can&#8217;t find any issue. I would love to hear from someone more experienced with race conditions in JavaScript, though.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DerickBailey?a=XeHBx3R6ztk:r4ex9KWLLyo:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=XeHBx3R6ztk:r4ex9KWLLyo:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=XeHBx3R6ztk:r4ex9KWLLyo:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=XeHBx3R6ztk:r4ex9KWLLyo:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=XeHBx3R6ztk:r4ex9KWLLyo:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=XeHBx3R6ztk:r4ex9KWLLyo:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=I9og5sOYxJI" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=XeHBx3R6ztk:r4ex9KWLLyo:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=XeHBx3R6ztk:r4ex9KWLLyo:bcOpcFrp8Mo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=bcOpcFrp8Mo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DerickBailey/~4/XeHBx3R6ztk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/derickbailey/2012/02/03/get-a-model-from-a-backbone-collection-without-knowing-if-the-collection-is-loaded/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://lostechies.com/derickbailey/2012/02/03/get-a-model-from-a-backbone-collection-without-knowing-if-the-collection-is-loaded/</feedburner:origLink></item>
		<item>
		<title>JavaScript File &amp; Folder Structures: Just Pick One</title>
		<link>http://feedproxy.google.com/~r/DerickBailey/~3/ODkkZo82XnY/</link>
		<comments>http://lostechies.com/derickbailey/2012/02/02/javascript-file-folder-structures-just-pick-one/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 13:29:31 +0000</pubDate>
		<dc:creator>Derick Bailey</dc:creator>
				<category><![CDATA[AntiPatterns]]></category>
		<category><![CDATA[Backbone]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Model-View-Controller]]></category>

		<guid isPermaLink="false">http://lostechies.com/derickbailey/?p=795</guid>
		<description>Rails wants you to put specific files in specific folder structures, based on the object type that will be in the file. Java demands that files in a folder structure are namespaced by that folder structure. VisualStudio also makes it&amp;#160;&amp;#8230; &lt;a href="http://lostechies.com/derickbailey/2012/02/02/javascript-file-folder-structures-just-pick-one/"&gt;Continue&amp;#160;reading&amp;#160;&lt;span class="meta-nav"&gt;&amp;#8594;&lt;/span&gt;&lt;/a&gt;</description>
			<content:encoded><![CDATA[<p>Rails wants you to put specific files in specific folder structures, based on the object type that will be in the file. Java demands that files in a folder structure are namespaced by that folder structure. VisualStudio also makes it seem like file / folder names should be the namespace / class name as well &#8211; but that&#8217;s just a good suggestion and not a requirement. Other languages and frameworks have some requirements for how you organize your files, too… with the exception of browser based JavaScript (… mostly…)</p>
<h2>JavaScript File Organization: You&#8217;re Doing It Right</h2>
<p>The reality of JavaScript in general web-based development (not talking about server side at all, here) is that it makes absolutely no difference how your files and folders are organized. Zero difference at all… at least as far as the JavaScript runtime is concerned.</p>
<p>The only thing that matters is that you include your files in your HTML with a &lt;script&gt; block, correctly. You also need to pay attention to which order they are included in most cases, to make sure things are defined before they are used (tools like RequireJS and other script loaders and module definition / loaders help with this).</p>
<p>What does this really mean? It means:</p>
<blockquote>
<p><strong><em>You&#8217;re Doing It RIGHT!</em></strong></p>
</blockquote>
<p>Yup. You&#8217;re doing it right, because it doesn&#8217;t matter how you do it.</p>
<p>What does matter, though, is that you and your team (if you have a team) pick an organizational convention and stick with it. It&#8217;s actually very more important for your team to have a good file and folder structure for your JavaScript. But you don&#8217;t need to worry about what that structure is. Pick a standard and use it. When it fails (and it will), re-work your structure so that it works within the newly understood constrains and move on.</p>
<p>Of course, that fact that your browser and it&#8217;s JavaScript runtime don&#8217;t care about your file and folder organization doesn&#8217;t I&#8217;m without <em>my</em> opinions on how files and folders should be organized.</p>
<p>For example&#8230;</p>
<h2>M, V and C Folders</h2>
<p>A lot of people organize JavaScript MV* application files in a folder structure like this (BackboneJS in this case):</p>
<p><img title="Screen Shot 2012-02-01 at 9.43.16 PM.png" src="http://lostechies.com/derickbailey/files/2012/02/Screen-Shot-2012-02-01-at-9.43.16-PM.png" border="0" alt="Screen Shot 2012 02 01 at 9 43 16 PM" width="417" height="80" /></p>
<p>To the best of my knowledge, this folder structure is based on the &#8220;models&#8221;, &#8220;views&#8221; and &#8220;controllers&#8221; folder structure that was popularized by Ruby on Rails. Sure others may have had it first, but it was Rails that made it popular. Other MVC framework followed suit and demanded that you put your controller objects in the controllers folder, your model objects in your models folder, etc. But unless you&#8217;re Rails (or another framework that wants to be like Rails), this folder structure is stupid.</p>
<p>I&#8217;m pretty sure that Rails uses this folder structure to assume the types of objects that are found within the files. And I know for sure that it uses file names to assume the class that will be defined within the file. That is, when rails sees a file called &#8220;/app/controllers/foo_controller.rb&#8221;, it expects to find a class called &#8220;FooController&#8221; and it expects that this class will inherit from some Rails controller base class. If these expectations are not met, errors are thrown to say so.</p>
<p>I understand why Rails does it this way: file and folder based conventions make it easy to assume what a file will contain, and that makes it easy for the runtime to optimize for performance when pre-loading and caching the code contained within the files. This makes sense to me in Rails because the convention is based on good ideas for optimizing the way Rails works and the way it looks for files and how it loads them.</p>
<p>But, unless you&#8217;re Rails or another framework that wants to assume certain files in certain folder contain certain code, this is a terrible way to organize files.</p>
<h2>The Junk Drawer</h2>
<p>There are some good examples of other standards along this line. For example, I tend to follow the convention of a &#8220;public&#8221; folder with &#8220;css&#8221;, &#8220;images&#8221;, and &#8220;javascripts&#8221; folders. But honestly, this folder structure exhibits many of the same problems of being stupid that organizing files in M, V, and C folders does.</p>
<p>The real problem with these types of folder structures is that they become junk drawers. Even DHH and the Rails core team recognize that this is a poor folder structure outside the confines of Rails+Ruby code. That&#8217;s one of the reasons they added the Asset Pipeline in Rails 3.1. DHH even called the &#8220;javascripts&#8221; folder a junk drawer, very directly, in a RailsConf keynote in 2011 (or was it 2010?) &#8211; complete with a slide showing a drawer full of junk.</p>
<p>With any application that moves beyond a trivial number of files, these content-type, mime-type, code-type and general type-based folder structures turn in to a bloated pile of junk that is very difficult to sift through. Who wants to look at a folder with 20, 50 or 100 files in it, when you only really care about 2, 5 or 10 of those files?</p>
<p>And what happens when you suddenly have an object type that doesn&#8217;t fit your pre-established conventions? You end with a &#8220;lib&#8221; folder, like Rails, which becomes the ultimate junk drawer. &#8220;It&#8217;s not a model? It&#8217;s not a controller? It goes in lib.&#8221; &#8211; no matter what the actual functionality contained within the file is. The &#8220;lib&#8221; folder is asking to be a junk drawer… demanding it, really. So, do you follow that same junk drawer convention for non-M, V or C type-based files in your JavaScript apps? That doesn&#8217;t any make sense to me.</p>
<h2>How I Organize Files: By Functionality</h2>
<p>I prefer to organize my JavaScript files the way I used to organize my C# files in .NET projects: by functional area of the application. That is, I group files together in folders based on the area of the application that they facilitate.</p>
<p>For example, my BBCloneMail application has the following folder structure for it&#8217;s JavaScript:</p>
<p><img title="Screen Shot 2012-02-01 at 9.47.12 PM.png" src="http://lostechies.com/derickbailey/files/2012/02/Screen-Shot-2012-02-01-at-9.47.12-PM.png" border="0" alt="Screen Shot 2012 02 01 at 9 47 12 PM" width="418" height="112" /></p>
<p>Note that I&#8217;m still using the &#8220;javascripts&#8221; parent folder, but underneath of that I&#8217;m organizing by functional area of the application. In the root &#8220;javascripts&#8221; folder, are the primary application files &#8211; the ones that define the overall application bits. In the &#8220;mail&#8221; folder are all of the files that relate to the &#8220;mail&#8221; application. And, in the &#8220;contacts&#8221; folder are all of the files that relate to the &#8220;contacts&#8221; application.</p>
<p>I don&#8217;t care what &#8220;type&#8221; is contained in the file. That&#8217;s a completely irrelevant way to organize files to me. It makes no sense for me to organize files this way because many of my files contain more than one &#8220;type&#8221; of object. For example, I often put very simple model, collection and view definitions that are very closely related, in the same file.</p>
<h2>Why Type-Based Folders Might Be A Good Idea</h2>
<p>In spite of all my over-opinionated hand-waiving above, there are some good reasons to use type based folders in JavaScript. One reason is asynchronous file loading based on conventions.</p>
<p>You might have a JavaScript app that makes use of a templating engine (of which there are dozens, these days). It&#8217;s not always a good idea to pre-load every possible template in to the user&#8217;s browser, for download size and performance reasons. Sometimes it makes sense to fetch the template that you want the first time it&#8217;s requested.</p>
<p>To do this, it might make sense to use a convention to retrieve the files. I&#8217;ve seen several Backbone apps that use a jQuery selector to load files, as one example of this. When a Backbone view specifies a template as &#8220;#my-view-template&#8221;, the application&#8217;s template manager would make a request to the server to load something along the lines of &#8220;/templates/my-view-template.html&#8221;.</p>
<p>If you&#8217;re trying to organize your templates in a functional area of the application, you&#8217;ll have the added overhead of inserting the functional area folder name, such as &#8220;/mail/templates/inbox-template.html&#8221; for an &#8220;Inbox&#8221; view in a &#8220;mail&#8221; app, trying to load an &#8220;#inbox-template&#8221; jQuery selector as the template to render.</p>
<p>So… there&#8217;s at least one possible reason to use a type-based folder. I would still stick the type-based folder name under my functional area, though. I don&#8217;t want to mix up the templates between my functional areas of the application, by accident.</p>
<h2>A Tradeoff: Folder Names vs File Names</h2>
<p>Here&#8217;s one potential trade-off for using functional folder names vs type based folder names: you might have to specify the type in the file name. For example, if you have a model type name &#8220;Person&#8221;, a collection type named &#8220;Persons&#8221;, and a view to represent a single person or a collection of persons, what do you call that view? If you&#8217;re organizing things by type, you can call every &#8220;Person&#8221; and &#8220;Persons&#8221;</p>
<p>This can be very confusing. I was recently working with a client who was using an editor that only shows the file name for the open files, and none of the folder path for the files. He ended up with 4 &#8220;person.js&#8221; files in his open file list. Which one was the Person model, view, router, or controller file? We had to open each file to find the one we needed, every time. So, we took the hit on the file names. The &#8220;person.js&#8221; file contained the person model, while &#8220;persons.js&#8221; contained the collection, &#8220;personviews.js&#8221; contained the view definitions and &#8220;personrouter.js&#8221; contained the router. Thus, we&#8217;ve moved the need for specifying the object type from the folder structure (with all it&#8217;s bad ideas for using that) to the file name.</p>
<p>I&#8217;ve read at least one blog post that advocated using type-based folder names specifically to avoid the &#8220;ugliness&#8221; of having type names in your files. I seriously laughed out loud when I read that. Whether the type is in the file name or folder name is a moot point. You&#8217;re likely going to end up specifying the type somewhere. I would much rather have it in my file names because it&#8217;s easier for me to see things grouped together based on functionality, than based on the type of object contained in a file.</p>
<h2>It&#8217;s Just An Opinion, And A Loose One At That</h2>
<p>My own use of these conventions and ideas is rather loose at this point. I don&#8217;t stick strictly to anything, and I mix and match based on the project type, number of files and other constraints that a given project presents. Because, like I said at the top of this egregiously long post, you&#8217;re doing it right.</p>
<p>No matter what file and folder structure you pick for you JavaScript apps (assuming you&#8217;re using a suite of libraries that doesn&#8217;t force you in to a specific folder structure), you&#8217;re doing it right. JavaScript in a browser environment really doesn&#8217;t care what the file and folder structure is. But that doesn&#8217;t mean we as developers shouldn&#8217;t care. Pick a file and folder structure that fits the constraints of your application and change the structure as your app&#8217;s constraints change.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DerickBailey?a=ODkkZo82XnY:85tgx-gdHIQ:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=ODkkZo82XnY:85tgx-gdHIQ:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=ODkkZo82XnY:85tgx-gdHIQ:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=ODkkZo82XnY:85tgx-gdHIQ:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=ODkkZo82XnY:85tgx-gdHIQ:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=ODkkZo82XnY:85tgx-gdHIQ:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=I9og5sOYxJI" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=ODkkZo82XnY:85tgx-gdHIQ:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=ODkkZo82XnY:85tgx-gdHIQ:bcOpcFrp8Mo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=bcOpcFrp8Mo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DerickBailey/~4/ODkkZo82XnY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/derickbailey/2012/02/02/javascript-file-folder-structures-just-pick-one/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://lostechies.com/derickbailey/2012/02/02/javascript-file-folder-structures-just-pick-one/</feedburner:origLink></item>
		<item>
		<title>Cleaning Out Git Remotes The Easy Way</title>
		<link>http://feedproxy.google.com/~r/DerickBailey/~3/cuTeetr7LKo/</link>
		<comments>http://lostechies.com/derickbailey/2012/01/31/cleaning-out-git-remotes-the-easy-way/#comments</comments>
		<pubDate>Tue, 31 Jan 2012 20:53:17 +0000</pubDate>
		<dc:creator>Derick Bailey</dc:creator>
				<category><![CDATA[Command Line]]></category>
		<category><![CDATA[Git]]></category>

		<guid isPermaLink="false">http://lostechies.com/derickbailey/?p=791</guid>
		<description>I had a rather large number of remote repositories set up in my Backbone.ModelBinding repository on my box, due to the wonderful community of contributors. But it was time for me to clean out the remotes as I no longer&amp;#160;&amp;#8230; &lt;a href="http://lostechies.com/derickbailey/2012/01/31/cleaning-out-git-remotes-the-easy-way/"&gt;Continue&amp;#160;reading&amp;#160;&lt;span class="meta-nav"&gt;&amp;#8594;&lt;/span&gt;&lt;/a&gt;</description>
			<content:encoded><![CDATA[<p>I had a rather large number of remote repositories set up in my Backbone.ModelBinding repository on my box, due to the wonderful community of contributors. But it was time for me to clean out the remotes as I no longer needed any of the old ones. To make it easy, I used a simple bash script:</p>
<blockquote>
<p>git remote | while read a; do<br />&gt; git remote rm $a<br />&gt; done</p>
</blockquote>
<p>This took care of removing every single remote that I had in my &#8216;git remote&#8217; list … including the &#8220;origin&#8221; that I actually did want, now that I think about it. :P</p>
<p>But my bash-scripting-fu is terrible, so I couldn&#8217;t figure out how to not destroy all of them. I tried adding an if statement in there to check if it&#8217;s not &#8220;origin&#8221;, but couldn&#8217;t get it to work. Anyone got some better bash-chops than me, and can point out how to do this?</p>
<p> </p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DerickBailey?a=cuTeetr7LKo:fTgmVg_eDuY:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=cuTeetr7LKo:fTgmVg_eDuY:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=cuTeetr7LKo:fTgmVg_eDuY:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=cuTeetr7LKo:fTgmVg_eDuY:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=cuTeetr7LKo:fTgmVg_eDuY:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=cuTeetr7LKo:fTgmVg_eDuY:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=I9og5sOYxJI" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=cuTeetr7LKo:fTgmVg_eDuY:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=cuTeetr7LKo:fTgmVg_eDuY:bcOpcFrp8Mo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=bcOpcFrp8Mo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DerickBailey/~4/cuTeetr7LKo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/derickbailey/2012/01/31/cleaning-out-git-remotes-the-easy-way/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://lostechies.com/derickbailey/2012/01/31/cleaning-out-git-remotes-the-easy-way/</feedburner:origLink></item>
		<item>
		<title>Don’t Rely Solely On jQuery’s “keyup” Event</title>
		<link>http://feedproxy.google.com/~r/DerickBailey/~3/qnL75XL2A3Y/</link>
		<comments>http://lostechies.com/derickbailey/2012/01/27/dont-rely-solely-on-jquerys-keyup-event/#comments</comments>
		<pubDate>Fri, 27 Jan 2012 14:09:05 +0000</pubDate>
		<dc:creator>Derick Bailey</dc:creator>
				<category><![CDATA[Backbone]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Test Automation]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://lostechies.com/derickbailey/?p=787</guid>
		<description>A few days ago I pushed some changes to the form validation up to my WatchMeCode website. I was trying to fix a scenario where a browser cache would have some of the data in the purchase form already filled&amp;#160;&amp;#8230; &lt;a href="http://lostechies.com/derickbailey/2012/01/27/dont-rely-solely-on-jquerys-keyup-event/"&gt;Continue&amp;#160;reading&amp;#160;&lt;span class="meta-nav"&gt;&amp;#8594;&lt;/span&gt;&lt;/a&gt;</description>
			<content:encoded><![CDATA[<p>A few days ago I pushed some changes to the form validation up to my <a href="http://watchmecode.net">WatchMeCode</a> website. I was trying to fix a scenario where a browser cache would have some of the data in the purchase form already filled in. In that scenario, a potential customer would have to modify each field, even though they were already filled in, in order for my  Backbone code to see the data in the field.</p>
<p>To &#8220;fix&#8221; the problem, I switched my code from a &#8220;change&#8221; event to a &#8220;keyup&#8221; event for the text boxes … bad idea!</p>
<h2>Browser Auto-Fill</h2>
<p>Most (if not all) browsers have an auto-fill feature, these days. I use it in Chrome a lot. It saves me a few seconds here and there and generally makes it easier for me to fill in the same repetitious information across websites.</p>
<p><img title="Screen Shot 2012-01-27 at 7.53.37 AM.png" src="http://lostechies.com/derickbailey/files/2012/01/Screen-Shot-2012-01-27-at-7.53.37-AM.png" border="0" alt="Screen Shot 2012 01 27 at 7 53 37 AM" width="423" height="361" /></p>
<p>But there&#8217;s a problem with auto-fill. It doesn&#8217;t fire the &#8220;keyup&#8221; event. It fires the &#8220;change&#8221; event for the things it fills in, but not &#8220;keyup&#8221;. This resulted in the data being truncated when it populated my Backbone model.</p>
<p>In the above screenshot, since i had typed &#8220;deri&#8221; in to the email address, the email that is stored in the Backbone model would only be &#8220;deri&#8221; &#8211; and that&#8217;s obviously not a valid email address.</p>
<h2>Easy To Fix</h2>
<p>There are a number of very easy ways to fix this.</p>
<ul>
<li>Validate the email address format</li>
<li>Use a combination of &#8220;blur&#8221;, &#8220;change&#8221;, and &#8220;keyup&#8221; events</li>
<li>Delay reading the data until the user clicks the &#8220;Purchase&#8221; button</li>
<li>Use a KVO (key-value observer) plugin like my Backbone.ModelBinding and let it deal with that for you</li>
</ul>
<p>For the quick-fix to get my site working properly, I went with the combination of &#8220;change&#8221; and &#8220;keyup&#8221; events. I&#8217;ll be re-writing my purchase form sometime soon, and will likely delay reading the values until they click the &#8220;Purchase&#8221; button. I&#8217;m also going to put in better email address validation to make sure it at least has an @ and a . in it, and I&#8217;ll likely use the HTML5 &#8220;email&#8221; field and see how that will help me, if at all.</p>
<h2>Not So Easy To Automate Testing</h2>
<p>When I originally made the change to use the &#8220;keyup&#8221; event, I did all my usual testing &#8211; which did not include using auto-fill. All of my testing passed, so I pushed the site live.</p>
<p>How do you test for bugs like this in an automated way? Is there even an automated way to test a browser&#8217;s auto-fill? I&#8217;d like to avoid mistakes like this in the future, and some automated testing around it would certainly be nice.</p>
<h2>Lesson Learned: Don&#8217;t Rely Solely On &#8220;keyup&#8221;</h2>
<p>There certainly are some great things you can do with the &#8220;keyup&#8221; event &#8211; like autocomplete, for one &#8211; but it&#8217;s not a great idea to only use this when there&#8217;s a chance that the browser&#8217;s auto-fill will be used.</p>
<p>And unfortunately for me, 2 of my customers ran in to this problem before I got it fixed. It makes it very hard to email someone the download instructions for their order. One of them contacted me and I corrected the order. But the other purchaser has not yet contacted me, and I don&#8217;t have enough information to figure out who they are, so I can&#8217;t track them down. I hope this person realizes that they didn&#8217;t get their order, they contact me. My contact info is all over the site… so … hopefully … the lessons learned for running an e-commerce site are sometimes painful.</p>
<p> </p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DerickBailey?a=qnL75XL2A3Y:VqS3Oev8PCU:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=qnL75XL2A3Y:VqS3Oev8PCU:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=qnL75XL2A3Y:VqS3Oev8PCU:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=qnL75XL2A3Y:VqS3Oev8PCU:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=qnL75XL2A3Y:VqS3Oev8PCU:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=qnL75XL2A3Y:VqS3Oev8PCU:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=I9og5sOYxJI" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=qnL75XL2A3Y:VqS3Oev8PCU:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=qnL75XL2A3Y:VqS3Oev8PCU:bcOpcFrp8Mo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=bcOpcFrp8Mo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DerickBailey/~4/qnL75XL2A3Y" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/derickbailey/2012/01/27/dont-rely-solely-on-jquerys-keyup-event/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://lostechies.com/derickbailey/2012/01/27/dont-rely-solely-on-jquerys-keyup-event/</feedburner:origLink></item>
		<item>
		<title>Modularity And Security In Composite JavaScript Apps</title>
		<link>http://feedproxy.google.com/~r/DerickBailey/~3/qu95KQaPUwk/</link>
		<comments>http://lostechies.com/derickbailey/2012/01/26/modularity-and-security-in-composite-javascript-apps/#comments</comments>
		<pubDate>Thu, 26 Jan 2012 13:44:16 +0000</pubDate>
		<dc:creator>Derick Bailey</dc:creator>
				<category><![CDATA[Backbone]]></category>
		<category><![CDATA[Backbone.Marionette]]></category>
		<category><![CDATA[Composite Apps]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://lostechies.com/derickbailey/?p=782</guid>
		<description>In one of my current apps for a client, I have an activity based security system that determines what the user is allowed to do. The trick to this system is that all of the authorization checks happen on the&amp;#160;&amp;#8230; &lt;a href="http://lostechies.com/derickbailey/2012/01/26/modularity-and-security-in-composite-javascript-apps/"&gt;Continue&amp;#160;reading&amp;#160;&lt;span class="meta-nav"&gt;&amp;#8594;&lt;/span&gt;&lt;/a&gt;</description>
			<content:encoded><![CDATA[<p>In one of my current apps for a client, I have <a href="http://lostechies.com/derickbailey/2011/05/24/dont-do-role-based-authorization-checks-do-activity-based-checks/">an activity based security system</a> that determines what the user is allowed to do. The trick to this system is that all of the authorization checks happen on the server, but the functionality that is being secured runs on the client, in JavaScript.</p>
<p>This is a bit of a problem. If I send all of the JavaScript that is uses to run any part of the system to the browser, then it&#8217;s possible that a clever user could enable it and do things they aren&#8217;t supposed to do. Of course, when they send a request back to the server, the server will verify they can do what they requested and block it… but the user should not be able to even try to do things they aren&#8217;t authorized to do, in the first place.</p>
<p>The solution that I&#8217;ve come up with, at a very high &#8220;functional area of the application&#8221; level, is simply not to send JavaScript to the browser if the user is not allowed to use it. This keeps me from having to do extra security checks in the browser, keeps the download for the user smaller and generally makes the app appear snappier because there is less code to run. More importantly, though, it keeps the user from being able to try things they can&#8217;t do.</p>
<h2>Modules To The Rescue</h2>
<p>I&#8217;m facilitating this through the use of modules in my JavaScript &#8211; both &#8220;module&#8221; as in the JavaScript module pattern, and &#8220;module&#8221; as in a packaged functional area of an application.</p>
<p>It&#8217;s worth noting, though, that I&#8217;m not using AMD (asynchronous module definitions), RequireJS, or any other &#8220;module&#8221; framework for JavaScript. The debate about the &#8220;right way&#8221; to do modules can rage on all it wants. I&#8217;m content with simple immediate functions and logical groupings of files while the more intelligent and invested people in the JS community figure that all out.</p>
<p>Each of the functional areas of my application is built in it&#8217;s own set of files. Each area has multiple files that it is composed within, but the files are grouped together for easy identification of what makes up a module. I also have an HTML template for each module which provides the needed &lt;script&gt; tags to include the code for that module.</p>
<h2>Only Render What Is Needed</h2>
<p>When I need a functional area of my site to be sent down to the user, I tell my server side template language to include the correct HTML file. For example, I&#8217;m doing this in an ASP.NET MVC application:</p>
<div id="gist-1680805" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'>@{var user = (CustomPrincipal)User;}</div><div class='line' id='LC2'><br/></div><div class='line' id='LC3'>@if (user.Can(&quot;locations/manage&quot;))</div><div class='line' id='LC4'>{</div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;@Html.LocationManagementScripts()</div><div class='line' id='LC6'>}</div><div class='line' id='LC7'><br/></div><div class='line' id='LC8'>@if (user.Can(&quot;locations/search&quot;))</div><div class='line' id='LC9'>{</div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;@Html.LocationSearchScripts()</div><div class='line' id='LC11'>}</div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1680805/10ca9fb5b64e7ddfa3503719503ff0bbad141af0/1.cshtml" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1680805#file_1.cshtml" style="float:right;margin-right:10px;color:#666">1.cshtml</a>
            <a href="https://gist.github.com/1680805">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>In this code, I&#8217;m checking to see if the current user is allowed to manage locations. If they are, the extension method &#8220;LocationManagementScripts&#8221; is called. This in turn renders the &#8220;LocationManagementScript.html&#8221; file at this point in my HTML layout. That file contains all of the &lt;script&gt; tags for the location management JavaScript app. In the same way, I&#8217;m checking to see if the user can search through locations, and running the same basic process if they can.</p>
<h2>Self-Initializing Modules</h2>
<p>When a functional module is included after passing one of these checks, it needs a way to get itself spun up and started so that it can do it&#8217;s magic. It may need to render something on to the screen. It may need to register itself with the application&#8217;s <a href="http://lostechies.com/derickbailey/2011/07/19/references-routing-and-the-event-aggregator-coordinating-views-in-backbone-js/">event aggregator</a>, or any of a number of other things. This is where my <a href="https://github.com/derickbailey/backbone.marionette">Backbone.Marionette</a> add-on comes in to play for my Backbone apps.</p>
<p>Marionette has an explicit concept of an &#8220;initializer&#8221; tied to it&#8217;s Application objects. When you create an instance of an Application object, you can call &#8220;app.addInitializer&#8221; and pass a callback function. The callback function represents everything that your module needs to do, to get itself up and running. All of these initializer functions &#8211; no matter how many you add &#8211; get fired when you call &#8220;app.start()&#8221;.</p>
<div id="gist-1680805" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="nx">myApp</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Backbone</span><span class="p">.</span><span class="nx">Marionette</span><span class="p">.</span><span class="nx">Application</span><span class="p">();</span></div><div class='line' id='LC2'><br/></div><div class='line' id='LC3'><span class="nx">myApp</span><span class="p">.</span><span class="nx">addInitializer</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">options</span><span class="p">){</span></div><div class='line' id='LC4'>&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">myView</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">MyView</span><span class="p">({</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">model</span><span class="o">:</span> <span class="nx">options</span><span class="p">.</span><span class="nx">someModel</span></div><div class='line' id='LC6'>&nbsp;&nbsp;<span class="p">});</span></div><div class='line' id='LC7'>&nbsp;&nbsp;<span class="nx">MyApp</span><span class="p">.</span><span class="nx">mainRegion</span><span class="p">.</span><span class="nx">show</span><span class="p">(</span><span class="nx">myView</span><span class="p">);</span></div><div class='line' id='LC8'><span class="p">});</span></div><div class='line' id='LC9'><br/></div><div class='line' id='LC10'><span class="nx">myApp</span><span class="p">.</span><span class="nx">addInitializer</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">options</span><span class="p">){</span></div><div class='line' id='LC11'>&nbsp;&nbsp;<span class="k">new</span> <span class="nx">MyRouter</span><span class="p">();</span></div><div class='line' id='LC12'>&nbsp;&nbsp;<span class="k">new</span> <span class="nx">SomeOtherView</span><span class="p">().</span><span class="nx">render</span><span class="p">();</span></div><div class='line' id='LC13'><span class="p">});</span></div><div class='line' id='LC14'><br/></div><div class='line' id='LC15'><span class="nx">myApp</span><span class="p">.</span><span class="nx">start</span><span class="p">();</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1680805/b56ae912ba7e6fd1546034081d2865ff623e9a4a/2.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1680805#file_2.js" style="float:right;margin-right:10px;color:#666">2.js</a>
            <a href="https://gist.github.com/1680805">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Each functional area of my application has it&#8217;s own initializer function. When a functional area has been included in the rendered &lt;script&gt; tags, the initializer gets added and when the &#8220;start&#8221; method is called, the modules for that functional area are fired up and they do there thing.</p>
<h2>A Composite App, And Sub-Apps</h2>
<p>One of the tricks to making all of this work, is that I need to have a primary &#8220;app&#8221; object that all of my modules know about. In the above example, the &#8220;myApp&#8221; object is this. Each of the modules for each of the functional areas has direct knowledge of this object and can call public APIs on it &#8211; including the &#8220;addInitializer&#8221; method.</p>
<p>A better example of what a module definition and initializer might look like, would be this:</p>
<div id="gist-1680805" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="c1">// --------------------</span></div><div class='line' id='LC2'><span class="c1">// app.js</span></div><div class='line' id='LC3'><br/></div><div class='line' id='LC4'><span class="nx">myApp</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Backbone</span><span class="p">.</span><span class="nx">Marionette</span><span class="p">.</span><span class="nx">Application</span><span class="p">();</span></div><div class='line' id='LC5'><br/></div><div class='line' id='LC6'><span class="nx">myApp</span><span class="p">.</span><span class="nx">addRegions</span><span class="p">({</span></div><div class='line' id='LC7'>&nbsp;&nbsp;<span class="nx">mainRegion</span><span class="o">:</span> <span class="s2">&quot;#main&quot;</span></div><div class='line' id='LC8'><span class="p">});</span></div><div class='line' id='LC9'><br/></div><div class='line' id='LC10'><br/></div><div class='line' id='LC11'><span class="c1">// --------------------</span></div><div class='line' id='LC12'><span class="c1">// locationSearch.js</span></div><div class='line' id='LC13'><br/></div><div class='line' id='LC14'><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">myApp</span><span class="p">,</span> <span class="nx">Backbone</span><span class="p">){</span></div><div class='line' id='LC15'>&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">SearchView</span> <span class="o">=</span> <span class="nx">Backbone</span><span class="p">.</span><span class="nx">View</span><span class="p">.</span><span class="nx">extend</span><span class="p">({</span></div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">// ...</span></div><div class='line' id='LC17'>&nbsp;&nbsp;<span class="p">});</span></div><div class='line' id='LC18'><br/></div><div class='line' id='LC19'>&nbsp;&nbsp;<span class="nx">myApp</span><span class="p">.</span><span class="nx">addRegions</span><span class="p">({</span></div><div class='line' id='LC20'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">searchRegion</span><span class="o">:</span> <span class="s2">&quot;#search&quot;</span></div><div class='line' id='LC21'>&nbsp;&nbsp;<span class="p">});</span></div><div class='line' id='LC22'><br/></div><div class='line' id='LC23'>&nbsp;&nbsp;<span class="nx">myApp</span><span class="p">.</span><span class="nx">addInitializer</span><span class="p">(</span><span class="kd">function</span><span class="p">(){</span></div><div class='line' id='LC24'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">var</span> <span class="nx">view</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">SearchView</span><span class="p">();</span></div><div class='line' id='LC25'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">view</span><span class="p">.</span><span class="nx">render</span><span class="p">();</span></div><div class='line' id='LC26'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nx">myApp</span><span class="p">.</span><span class="nx">searchRegion</span><span class="p">.</span><span class="nx">show</span><span class="p">(</span><span class="nx">view</span><span class="p">);</span></div><div class='line' id='LC27'>&nbsp;&nbsp;<span class="p">});</span></div><div class='line' id='LC28'><span class="p">})(</span><span class="nx">myApp</span><span class="p">,</span> <span class="nx">Backbone</span><span class="p">);</span></div><div class='line' id='LC29'><br/></div><div class='line' id='LC30'><br/></div><div class='line' id='LC31'><span class="c1">// --------------------</span></div><div class='line' id='LC32'><span class="c1">// index.html</span></div><div class='line' id='LC33'><br/></div><div class='line' id='LC34'><span class="o">&lt;</span><span class="nx">script</span> <span class="nx">language</span><span class="o">=</span><span class="s2">&quot;javascript&quot;</span><span class="o">&gt;</span></div><div class='line' id='LC35'>&nbsp;&nbsp;<span class="nx">myApp</span><span class="p">.</span><span class="nx">start</span><span class="p">();</span></div><div class='line' id='LC36'><span class="o">&lt;</span><span class="err">/script&gt;</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1680805/e61b4b20a7a216a4d8c9d6bfd95848edf35dff73/3.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1680805#file_3.js" style="float:right;margin-right:10px;color:#666">3.js</a>
            <a href="https://gist.github.com/1680805">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>In this example, I&#8217;m using the simple JavaScript module pattern to encapsulate my search functionality. I&#8217;m also providing an initializer for the module that instantiates a search view and shows it to the user using a <a href="http://lostechies.com/derickbailey/2011/12/12/composite-js-apps-regions-and-region-managers/">region manager</a>.</p>
<p>Each of these functional areas is basically a sub-application. Many sub-applications are used to compose a larger application and overall experience for the user. The composition of a larger application through various modules that are included / excluded based on some criteria are what really make this a composite application.</p>
<p>I also included the final call to &#8220;myApp.start()&#8221;, showing that I do this from my main HTML page and not from my JavaScript files. This provides a single point of entry for all of the registered modules, no matter which modules are registered. The &#8220;myApp&#8221; object really doesn&#8217;t care which modules are registered, honestly. It doesn&#8217;t need to care. It only needs to execute the initializers that happen to be present. If none are present because the user didn&#8217;t have permission to do anything, then nothing happens when this method is called and the user won&#8217;t see anything.</p>
<h2>Security: Don&#8217;t Let Them See It If They Can&#8217;t Do It</h2>
<p>If the security check to see if the user is allowed to use the location search feature fails, the rendered HTML won&#8217;t include the &lt;script&gt; tags for the &#8220;locationSearch.js&#8221; file. If this file is not sent down to the browser, then it will never register itself. If a module has not registered itself for initialization, it&#8217;s views won&#8217;t show up on the screen and the user won&#8217;t be able to try and use the feature. Further, the user won&#8217;t be able to &#8220;view source&#8221; on the page and find any stray JavaScript that they shouldn&#8217;t be able to use.</p>
<h2>It&#8217;s Not Always That Easy</h2>
<p>Of course there are other security concerns that are not this simple. When a functional area is closed off by authorization, it&#8217;s easy to keep things clean like this. We can compose the application at run time simply by including the right files and letting the code in those files register themselves for initialization. But when we have a functional area of the system that has finer grained authorization and permissions associated with it, things get a little more tricky.</p>
<p>I&#8217;m still learning and exploring this space. I have some ideas and am going to be implementing some of them soon. If anyone out there has any experience in handling finer grained security needs in JavaScript apps, I&#8217;d love to hear about it. Post links to your favorite resources for this, in the comments.</p>
<p> </p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DerickBailey?a=qu95KQaPUwk:RAcw-0evDaE:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=qu95KQaPUwk:RAcw-0evDaE:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=qu95KQaPUwk:RAcw-0evDaE:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=qu95KQaPUwk:RAcw-0evDaE:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=qu95KQaPUwk:RAcw-0evDaE:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=qu95KQaPUwk:RAcw-0evDaE:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=I9og5sOYxJI" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=qu95KQaPUwk:RAcw-0evDaE:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=qu95KQaPUwk:RAcw-0evDaE:bcOpcFrp8Mo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=bcOpcFrp8Mo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DerickBailey/~4/qu95KQaPUwk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/derickbailey/2012/01/26/modularity-and-security-in-composite-javascript-apps/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		<feedburner:origLink>http://lostechies.com/derickbailey/2012/01/26/modularity-and-security-in-composite-javascript-apps/</feedburner:origLink></item>
		<item>
		<title>Rant: That’s Not Rest.</title>
		<link>http://feedproxy.google.com/~r/DerickBailey/~3/PPJ7T6xec-U/</link>
		<comments>http://lostechies.com/derickbailey/2012/01/25/rant-thats-not-rest/#comments</comments>
		<pubDate>Wed, 25 Jan 2012 13:22:34 +0000</pubDate>
		<dc:creator>Derick Bailey</dc:creator>
				<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://lostechies.com/derickbailey/?p=770</guid>
		<description>I&amp;#8217;ve asked for an explanation, definition, blog post, book, or any other source of material that can get me up to speed on REST in web development a number of times. It&amp;#8217;s a popular subject these days, and there seems&amp;#160;&amp;#8230; &lt;a href="http://lostechies.com/derickbailey/2012/01/25/rant-thats-not-rest/"&gt;Continue&amp;#160;reading&amp;#160;&lt;span class="meta-nav"&gt;&amp;#8594;&lt;/span&gt;&lt;/a&gt;</description>
			<content:encoded><![CDATA[<p>I&#8217;ve asked for an explanation, definition, blog post, book, or any other source of material that can get me up to speed on <a href="http://en.wikipedia.org/wiki/Representational_state_transfer">REST in web development</a> a number of times. It&#8217;s a popular subject these days, and there seems to be an abundance of knowledge and information out there.</p>
<p>Except that it&#8217;s all wrong. Every last bit of it.</p>
<p>… or, at least the handful of people who inevitably respond with comments like &#8220;no one does REST correctly&#8221; and &#8220;that&#8217;s not REST&#8221; would have me believe.</p>
<h2>Your Doing It Wrong</h2>
<p>Frankly, I&#8217;m tired of this pedantic, obnoxious response. The same people that continuously say &#8220;no one does it right&#8221; can&#8217;t seem to tell me why it&#8217;s wrong or point me to a resource that does do it right.</p>
<p><img title="ThatsNotREST.jpg" src="http://lostechies.com/derickbailey/files/2012/01/ThatsNotREST.jpg" border="0" alt="ThatsNotREST" width="500" height="503" /></p>
<p>Here&#8217;s the deal. If everyone does it wrong, then write a blog post or a book or a screencast or something that tells the world how to do it right. Until you can point people to what REST actually is, stop telling everyone that no one does REST right.</p>
<h2>My Journey Into Being Wrong</h2>
<p>I have work to do. I&#8217;m obviously going to do it wrong, but frankly, I don&#8217;t care at this point. My system will work just fine, just like every other &#8220;That&#8217;s not REST&#8221; system out there.</p>
<p>To help me learn how to be wrong, though, here are a few resources that I&#8217;m going to be checking out:</p>
<p><a href="http://getsomere.st/">Get Some REST</a>: A work in progress book from Steve Klabnik. I signed up for the mailing list and am eagerly waiting. There&#8217;s rumor that Steve might actually be doing it right.</p>
<p><a href="http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596529260">RESTFul Web Services</a> &#8211; I bought the Kindle version last night. It&#8217;s the book DHH says everyone should read and a few others also suggested it.</p>
<p><a href="http://www.amazon.com/REST-Practice-Hypermedia-Systems-Architecture/dp/0596805829">REST In Practice</a> &#8211; I&#8217;m probably going to buy this one, too. It seems to have the &#8220;30,000 foot view&#8221; that I&#8217;m also looking for, according to one reviewer on Amazon.</p>
<p>If anyone else has any resources for how I can learn non-REST, RESTful best practices, I&#8217;d love to know.</p>
<p>(end of rant)</p>
<p> </p>
<p><span style="font-size: 18px; font-weight: bold;">… Updates</span></p>
<p>Thanks to everyone who is responding in the comments here and via twitter. I&#8217;m going to update this post with the resources that people are pointing me to, from Twitter.</p>
<p>The majority of my experience with anything REST-like comes from working with Ruby on Rails, and mimicking it&#8217;s handling of HTTP verbs with Sinatra application. I know this isn&#8217;t anything near correct, which is why I&#8217;m looking to find good resources.</p>
<p>I&#8217;ve been getting a lot of &#8220;you don&#8217;t need to do pure REST&#8221; responses &#8211; which I agree with. One of my problems, though, is that I&#8217;m having a hard time figuring out what &#8220;pure&#8221; REST is so that I can know the difference between that and what I&#8217;m actually doing.</p>
<p><a href="https://twitter.com/#!/serialseb/status/162172630844186624">Sebastian Lambla points out</a> that it&#8217;s not the entire REST community that pulls this crap. There are plenty of people that are helping, providing good information and creating good resources to throw at people like me that are wanting to learn. My problem is not with the REST community as a whole, but with the people that behave in the way I&#8217;ve pointed out, here.</p>
<p>The most consistent advice I&#8217;m seeing so far, is to start with the books I&#8217;ve listed / purchases already. That will at least get me heading down a better direction.</p>
<h2>Resources From The Twitterverse</h2>
<p><a href="http://www.amazon.com/RESTful-Web-Services-Cookbook-Scalability/dp/0596801688">http://www.amazon.com/RESTful-Web-Services-Cookbook-Scalability/dp/0596801688</a></p>
<p><a href="http://code.google.com/p/implementing-rest/">http://code.google.com/p/implementing-rest/</a></p>
<p><a href="http://www.amazon.com/REST-Design-Rulebook-Mark-Masse/dp/1449310508">http://www.amazon.com/REST-Design-Rulebook-Mark-Masse/dp/1449310508</a></p>
<p>The #rest channel on <a href="http://freenode.net/">http://freenode.net/</a> IRC</p>
<p><a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm">http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm</a></p>
<p><a href="http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven">http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven</a></p>
<p><a href="http://amundsen.com/blog/">http://amundsen.com</a></p>
<p><a href="http://www.infoq.com/search.action?queryString=stefan+tilkov+rest&amp;searchOrder=relevance&amp;search=stefan+tilkov+rest">http://www.infoq.com/search.action?queryString=stefan+tilkov+rest&amp;searchOrder=relevance&amp;search=stefan+tilkov+rest</a></p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DerickBailey?a=PPJ7T6xec-U:AyWUvRIHoS0:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=PPJ7T6xec-U:AyWUvRIHoS0:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=PPJ7T6xec-U:AyWUvRIHoS0:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=PPJ7T6xec-U:AyWUvRIHoS0:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=PPJ7T6xec-U:AyWUvRIHoS0:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=PPJ7T6xec-U:AyWUvRIHoS0:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=I9og5sOYxJI" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=PPJ7T6xec-U:AyWUvRIHoS0:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=PPJ7T6xec-U:AyWUvRIHoS0:bcOpcFrp8Mo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=bcOpcFrp8Mo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DerickBailey/~4/PPJ7T6xec-U" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/derickbailey/2012/01/25/rant-thats-not-rest/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		<feedburner:origLink>http://lostechies.com/derickbailey/2012/01/25/rant-thats-not-rest/</feedburner:origLink></item>
		<item>
		<title>Some Thoughts On Functional JavaScript</title>
		<link>http://feedproxy.google.com/~r/DerickBailey/~3/ocqOgyYF3Fg/</link>
		<comments>http://lostechies.com/derickbailey/2012/01/24/some-thoughts-on-functional-javascript/#comments</comments>
		<pubDate>Tue, 24 Jan 2012 13:29:08 +0000</pubDate>
		<dc:creator>Derick Bailey</dc:creator>
				<category><![CDATA[DSL]]></category>
		<category><![CDATA[Functional]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://lostechies.com/derickbailey/?p=758</guid>
		<description>Just for fun I decided to put together a quick sample of some functional JavaScript &amp;#8211; as in, functional programming done with JavaScript. I&amp;#8217;m not really very familiar with functional languages other than playing with Haskell a bit and doing&amp;#160;&amp;#8230; &lt;a href="http://lostechies.com/derickbailey/2012/01/24/some-thoughts-on-functional-javascript/"&gt;Continue&amp;#160;reading&amp;#160;&lt;span class="meta-nav"&gt;&amp;#8594;&lt;/span&gt;&lt;/a&gt;</description>
			<content:encoded><![CDATA[<p>Just for fun I decided to put together a quick sample of some functional JavaScript &#8211; as in, <a href="http://en.wikipedia.org/wiki/Functional_programming">functional programming</a> done with JavaScript. I&#8217;m not really very familiar with functional languages other than playing with Haskell a bit and doing some functional-style stuff in C# and Ruby. I wanted to see what a functional JavaScript code base might look like.</p>
<h2>A Functional Calculator</h2>
<p>To keep things simple, I created a calculator using nothing but functions. Each function takes other functions as parameters and returns a function. The only exception to this is the simple `value` function which takes a value and returns a function that itself will return the original value.</p>
<p>Here&#8217;s the basic code I wrote for my calculator, including the aforementioned `value` function:</p>
<div id="gist-1660207" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="c1">// A raw value, represented as a function</span></div><div class='line' id='LC2'><span class="kd">var</span> <span class="nx">value</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">val</span><span class="p">){</span></div><div class='line' id='LC3'>&nbsp;&nbsp;<span class="k">return</span> <span class="kd">function</span><span class="p">(){</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="nx">val</span><span class="p">;</span></div><div class='line' id='LC5'>&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC6'><span class="p">}</span></div><div class='line' id='LC7'><br/></div><div class='line' id='LC8'><span class="c1">// A function to add two functions together</span></div><div class='line' id='LC9'><span class="kd">var</span> <span class="nx">add</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">){</span></div><div class='line' id='LC10'>&nbsp;&nbsp;<span class="k">return</span> <span class="kd">function</span><span class="p">(){</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="nx">x</span><span class="p">()</span> <span class="o">+</span> <span class="nx">y</span><span class="p">();</span></div><div class='line' id='LC12'>&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC13'><span class="p">}</span></div><div class='line' id='LC14'><br/></div><div class='line' id='LC15'><span class="c1">// A function to subtract one function from another</span></div><div class='line' id='LC16'><span class="kd">var</span> <span class="nx">subtract</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">){</span></div><div class='line' id='LC17'>&nbsp;&nbsp;<span class="k">return</span> <span class="kd">function</span><span class="p">(){</span></div><div class='line' id='LC18'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="nx">x</span><span class="p">()</span> <span class="o">-</span> <span class="nx">y</span><span class="p">();</span></div><div class='line' id='LC19'>&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC20'><span class="p">}</span></div><div class='line' id='LC21'><br/></div><div class='line' id='LC22'><span class="c1">// A function to multiply two functions</span></div><div class='line' id='LC23'><span class="kd">var</span> <span class="nx">multiply</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">){</span></div><div class='line' id='LC24'>&nbsp;&nbsp;<span class="k">return</span> <span class="kd">function</span><span class="p">(){</span></div><div class='line' id='LC25'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="nx">x</span><span class="p">()</span> <span class="o">*</span> <span class="nx">y</span><span class="p">();</span></div><div class='line' id='LC26'>&nbsp;&nbsp;<span class="p">}</span></div><div class='line' id='LC27'><span class="p">}</span></div><div class='line' id='LC28'><br/></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1660207/96c7c067d3686ea9d97b75bfe931066cc2525499/funcalc.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1660207#file_funcalc.js" style="float:right;margin-right:10px;color:#666">funcalc.js</a>
            <a href="https://gist.github.com/1660207">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>I wrote all this through the use of some Jasmine tests, but as a quick example of how it can work, here&#8217;s a simple formula and result:</p>
<div id="gist-1660207" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="kd">var</span> <span class="nx">one</span> <span class="o">=</span> <span class="nx">value</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span></div><div class='line' id='LC2'><span class="kd">var</span> <span class="nx">two</span> <span class="o">=</span> <span class="nx">value</span><span class="p">(</span><span class="mi">2</span><span class="p">);</span></div><div class='line' id='LC3'><span class="kd">var</span> <span class="nx">three</span> <span class="o">=</span> <span class="nx">value</span><span class="p">(</span><span class="mi">3</span><span class="p">);</span></div><div class='line' id='LC4'><span class="kd">var</span> <span class="nx">four</span> <span class="o">=</span> <span class="nx">value</span><span class="p">(</span><span class="mi">4</span><span class="p">);</span></div><div class='line' id='LC5'><br/></div><div class='line' id='LC6'><span class="c1">// (1 + 2) * 3 - 4 == 5</span></div><div class='line' id='LC7'><span class="kd">var</span> <span class="nx">resultFunc</span> <span class="o">=</span> <span class="nx">subtract</span><span class="p">(</span><span class="nx">multiply</span><span class="p">(</span><span class="nx">add</span><span class="p">(</span><span class="nx">one</span><span class="p">,</span> <span class="nx">two</span><span class="p">),</span> <span class="nx">three</span><span class="p">),</span> <span class="nx">four</span><span class="p">);</span></div><div class='line' id='LC8'><br/></div><div class='line' id='LC9'><span class="c1">// but it&#39;s still a function right now, so evaluate it</span></div><div class='line' id='LC10'><span class="kd">var</span> <span class="nx">result</span> <span class="o">=</span> <span class="nx">resultFunc</span><span class="p">();</span></div><div class='line' id='LC11'><span class="nx">consol</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">result</span><span class="p">);</span> <span class="c1">// =&gt; 5</span></div><div class='line' id='LC12'><br/></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1660207/f6a3d87f8146b869d42b3436a288ca1746017c1e/sample.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1660207#file_sample.js" style="float:right;margin-right:10px;color:#666">sample.js</a>
            <a href="https://gist.github.com/1660207">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<h2>My Thoughts And Reactions</h2>
<p>These are the interesting points that stand out in my head. I&#8217;m not sure if these are &#8220;correct&#8221; or not… it&#8217;s just what pops out in my mind.</p>
<p>If anyone has any corrections and additional thoughts or notes, I&#8217;d love to hear them &#8211; just drop me a line in the comments, below.</p>
<h4>Functions And Functions As State</h4>
<p>I&#8217;ve represented everything as a function &#8211; even the simple values of 1 through 4. And every function returns a function, except for the simple values, which return a function that returns the actual value.</p>
<p><img title="FunctionAllTheThings.jpg" src="http://lostechies.com/derickbailey/files/2012/01/FunctionAllTheThings.jpg" border="0" alt="FunctionAllTheThings" width="400" height="300" /></p>
<p>In the process of returning functions from functions, I&#8217;m representing the state of the application as a series of functions.</p>
<p>This one is a bit odd for me to wrap my head around. I&#8217;m not sure if this is really correct, or if it&#8217;s just an oversimplification of what&#8217;s really happening here. There are no data-structures, though, only functions. So it stands to reason that the state is stored as a series of functions that can be evaluated to produce a result.</p>
<p><strong>Update</strong>: The Wikipedia article on <a href="http://en.wikipedia.org/wiki/Functional_programming">functional programming</a> says that fp &#8220;avoids state&#8221;. So… am I wrong in thinking that I&#8217;ve represented the state with functions instead of data structures?</p>
<h4>Funcional Command Pattern</h4>
<p>The result isn&#8217;t actually evaluated until I invoke the`resultFunc` in the above example. But I have the `resultFunc`available as a variable and I can pass it around anywhere I want. This basically turns it into a command pattern implementation, only in a functional manner instead of an object manner.</p>
<h4>Compose-able And DSL Functions</h4>
<p>All of these functions are side effect free. None of them actually mutates any existing application state. Of course this is a really simple implementation, but that was one of my goals. I&#8217;ll need to play with some more complex ideas in order to really see how side effect free would play out.</p>
<p>One of the benefits of side effect free functions is that the code in the sample is far more declarative and compose-able than most code I write. Since each function does one very small and very simple thing, taking in other functions as parameters, it&#8217;s easy to build things.</p>
<div id="gist-1660207" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="kd">var</span> <span class="nx">one</span> <span class="o">=</span> <span class="nx">value</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span></div><div class='line' id='LC2'><span class="kd">var</span> <span class="nx">two</span> <span class="o">=</span> <span class="nx">value</span><span class="p">(</span><span class="mi">2</span><span class="p">);</span></div><div class='line' id='LC3'><span class="kd">var</span> <span class="nx">three</span> <span class="o">=</span> <span class="nx">value</span><span class="p">(</span><span class="mi">3</span><span class="p">);</span></div><div class='line' id='LC4'><span class="kd">var</span> <span class="nx">four</span> <span class="o">=</span> <span class="nx">value</span><span class="p">(</span><span class="mi">4</span><span class="p">);</span></div><div class='line' id='LC5'><br/></div><div class='line' id='LC6'><span class="c1">// (1 + 2) * 3 - 4 == 5</span></div><div class='line' id='LC7'><span class="kd">var</span> <span class="nx">added</span> <span class="o">=</span> <span class="nx">add</span><span class="p">(</span><span class="nx">one</span><span class="p">,</span> <span class="nx">two</span><span class="p">)</span></div><div class='line' id='LC8'><span class="kd">var</span> <span class="nx">multiplied</span> <span class="o">=</span> <span class="nx">multiply</span><span class="p">(</span><span class="nx">added</span><span class="p">,</span> <span class="nx">three</span><span class="p">)</span></div><div class='line' id='LC9'><span class="kd">var</span> <span class="nx">resultFunc</span> <span class="o">=</span> <span class="nx">subtract</span><span class="p">(</span><span class="nx">multiplied</span><span class="p">,</span> <span class="nx">four</span><span class="p">);</span></div><div class='line' id='LC10'><br/></div><div class='line' id='LC11'><span class="c1">// the result is the same. </span></div><div class='line' id='LC12'><span class="c1">// it&#39;s been composed the same, functionally</span></div><div class='line' id='LC13'><span class="c1">// it was just put together with more variables in the mix</span></div><div class='line' id='LC14'><span class="kd">var</span> <span class="nx">result</span> <span class="o">=</span> <span class="nx">resultFunc</span><span class="p">();</span></div><div class='line' id='LC15'><span class="nx">consol</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">result</span><span class="p">);</span> <span class="c1">// =&gt; 5</span></div><div class='line' id='LC16'><br/></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1660207/57d657c16e82fd1f3de01449a9f42bc3b1ac5a57/compose.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1660207#file_compose.js" style="float:right;margin-right:10px;color:#666">compose.js</a>
            <a href="https://gist.github.com/1660207">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>This is something that I&#8217;ve played with in other languages, and I like this aspect of functional programming. It&#8217;s a great way to build DSLs for example.</p>
<h4>Compared To Object / Prototypal</h4>
<p>Oscar Godson posted <a href="http://jsbin.com/atopek/edit#javascript">a version of my code alongside a prototypal version</a> for a comparison.</p>
<div id="gist-1660207" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="cm">/**</span></div><div class='line' id='LC2'><span class="cm"> Prototypal</span></div><div class='line' id='LC3'><span class="cm"> from Oscar Godson: http://jsbin.com/atopek/edit#javascript</span></div><div class='line' id='LC4'><span class="cm">*/</span></div><div class='line' id='LC5'><br/></div><div class='line' id='LC6'><span class="kd">var</span> <span class="nx">Calc</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(){</span></div><div class='line' id='LC7'>&nbsp;&nbsp;<span class="k">this</span><span class="p">.</span><span class="nx">sum</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="c1">//could be a param</span></div><div class='line' id='LC8'>&nbsp;&nbsp;<span class="k">return</span> <span class="k">this</span><span class="p">;</span></div><div class='line' id='LC9'><span class="p">}</span></div><div class='line' id='LC10'><br/></div><div class='line' id='LC11'><span class="nx">Calc</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">add</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">x</span><span class="p">){</span></div><div class='line' id='LC12'>&nbsp;&nbsp;<span class="k">this</span><span class="p">.</span><span class="nx">sum</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">sum</span> <span class="o">+</span> <span class="nx">x</span><span class="p">;</span></div><div class='line' id='LC13'>&nbsp;&nbsp;<span class="k">return</span> <span class="k">this</span><span class="p">;</span></div><div class='line' id='LC14'><span class="p">}</span></div><div class='line' id='LC15'><br/></div><div class='line' id='LC16'><span class="nx">Calc</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">multiply</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">x</span><span class="p">){</span></div><div class='line' id='LC17'>&nbsp;&nbsp;<span class="k">this</span><span class="p">.</span><span class="nx">sum</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">sum</span> <span class="o">*</span> <span class="nx">x</span></div><div class='line' id='LC18'>&nbsp;&nbsp;<span class="k">return</span> <span class="k">this</span><span class="p">;</span></div><div class='line' id='LC19'><span class="p">}</span></div><div class='line' id='LC20'>&nbsp;&nbsp;</div><div class='line' id='LC21'><span class="nx">Calc</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">subtract</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">x</span><span class="p">){</span></div><div class='line' id='LC22'>&nbsp;&nbsp;<span class="k">this</span><span class="p">.</span><span class="nx">sum</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">sum</span> <span class="o">-</span> <span class="nx">x</span><span class="p">;</span></div><div class='line' id='LC23'>&nbsp;&nbsp;<span class="k">return</span> <span class="k">this</span></div><div class='line' id='LC24'><span class="p">}</span></div><div class='line' id='LC25'><br/></div><div class='line' id='LC26'><span class="nx">Calc</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">result</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(){</span></div><div class='line' id='LC27'>&nbsp;&nbsp;<span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">sum</span><span class="p">;</span></div><div class='line' id='LC28'><span class="p">}</span></div><div class='line' id='LC29'><br/></div><div class='line' id='LC30'><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="k">new</span> <span class="nx">Calc</span><span class="p">().</span><span class="nx">add</span><span class="p">(</span><span class="mi">1</span><span class="p">).</span><span class="nx">add</span><span class="p">(</span><span class="mi">2</span><span class="p">).</span><span class="nx">multiply</span><span class="p">(</span><span class="mi">3</span><span class="p">).</span><span class="nx">subtract</span><span class="p">(</span><span class="mi">4</span><span class="p">).</span><span class="nx">result</span><span class="p">())</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1660207/02afccd0e98abeb50dd74ce0d48e17223dad8cfc/prototypal.js" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1660207#file_prototypal.js" style="float:right;margin-right:10px;color:#666">prototypal.js</a>
            <a href="https://gist.github.com/1660207">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>I like seeing them side by side. It&#8217;s interesting the see all of the different ways that JavaScript can do the same thing. It also shows me just how ugly I think the functional version is. When you compare the actual formula in the comments to the functional JS code, the code is inside-out-backwards. The prototypal code with it&#8217;s method chaining is closer to the formula, though it&#8217;s still a bit off.</p>
<p>I think it&#8217;s easier to read and understand the chaining, though. It also reminds me of LINQ and monads &#8211; pipes and filters with a single result coming from the end of it.</p>
<h4>More Fun Functional Stuff To Try</h4>
<p>I haven&#8217;t done anything like memoizing or currying for these simple examples, but those are ideas I want to play with, too. I&#8217;ve written a currying function in JavaScript once or twice, and there&#8217;s plenty of examples in the good JS books. Memoizing is also available in Underscore.js but should be trivial to implement a naive version of it. I&#8217;m sure there are plenty of other things that would be fun to try, as well.</p>
<p><span style="font-size: 18px; font-weight: bold;">Code And Continuing Thoughts (Maybe)</span></p>
<p>If you&#8217;re interested in seeing this code, <a href="https://github.com/derickbailey/jsfuncalc">it&#8217;s on Github</a>.</p>
<p>I&#8217;m thinking about taking this a little further over time, just for fun. I&#8217;ve posted these comments in the read me (actually &#8211; they started there…) and I&#8217;ll continue to update the read me as I progress (assuming I actually do continue exploring this and don&#8217;t just forget about it like so many other things).</p>
<p>This is really pretty simple stuff&#8230; but it&#8217;s fun to write asimple exercise like this and think about what&#8217;s going on, why and see how it affects the way I think and approach software development.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/DerickBailey?a=ocqOgyYF3Fg:ks_fJKFwXSI:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=ocqOgyYF3Fg:ks_fJKFwXSI:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=ocqOgyYF3Fg:ks_fJKFwXSI:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/DerickBailey?i=ocqOgyYF3Fg:ks_fJKFwXSI:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=ocqOgyYF3Fg:ks_fJKFwXSI:dnMXMwOfBR0"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=dnMXMwOfBR0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=ocqOgyYF3Fg:ks_fJKFwXSI:I9og5sOYxJI"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=I9og5sOYxJI" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=ocqOgyYF3Fg:ks_fJKFwXSI:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/DerickBailey?a=ocqOgyYF3Fg:ks_fJKFwXSI:bcOpcFrp8Mo"><img src="http://feeds.feedburner.com/~ff/DerickBailey?d=bcOpcFrp8Mo" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DerickBailey/~4/ocqOgyYF3Fg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://lostechies.com/derickbailey/2012/01/24/some-thoughts-on-functional-javascript/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		<feedburner:origLink>http://lostechies.com/derickbailey/2012/01/24/some-thoughts-on-functional-javascript/</feedburner:origLink></item>
	</channel>
</rss><!-- Dynamic page generated in 0.912 seconds. --><!-- Cached page generated by WP-Super-Cache on 2012-02-09 09:56:11 --><!-- Compression = gzip -->

