<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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/"
	>

<channel>
	<title>unscriptable.com</title>
	<atom:link href="http://unscriptable.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://unscriptable.com</link>
	<description>Nothing is impossible. Even on the web.</description>
	<lastBuildDate>Fri, 03 May 2013 02:38:33 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Closures for Dummies (or why IIFE !== closure)</title>
		<link>http://unscriptable.com/2011/10/02/closures-for-dummies-or-why-iife-closure/</link>
		<comments>http://unscriptable.com/2011/10/02/closures-for-dummies-or-why-iife-closure/#comments</comments>
		<pubDate>Sun, 02 Oct 2011 21:31:47 +0000</pubDate>
		<dc:creator>John Hann</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://unscriptable.com/?p=802</guid>
		<description><![CDATA[I was going to see if I could craft a twitter-friendly 140-char explanation of the differences between IIFEs and closures.  A noble cause, for sure, especially since I suspect that the reason that there is so much confusion is that lots of explanations are either tl;dr or too technical.]]></description>
				<content:encoded><![CDATA[<p>There are lots of blog posts and online articles about javascript closures.  Many of them are well written.  Closures have also been discussed at length <a href="http://www.aminutewithbrendan.com/pages/20110216">with Brendan Eich</a>.  I really shouldn&#8217;t have to write another blog post.  Yet, here I am.  </p>
<p>Why?  Because I still see many people misusing the term, &#8220;closure&#8221;.  Specifically, I see people confusing <a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/">IIFE</a>s with closures.</p>
<p>I was going to see if I could craft a twitter-friendly 140-char explanation of the differences between IIFEs and closures.  A noble cause, for sure, especially since I suspect that the reason that there&#8217;s so much confusion is that many of the explanations are either tl;dr or too technical.  </p>
<p>140 characters may have been too ambitious.  Let&#8217;s see if I can do it in 140 <em>words</em> or less.  Starting&#8230; <strong>now</strong>.  Well, not including code snippets, mmkay? OK. Starting&#8230; <strong>now</strong>.<br />
<span id="more-802"></span></p>
<p><strong>[update 2011-10-04] Turns out I am wrong! <em>Who would have guessed that??!?!</em> I&#8217;ll post an update shortly to explain that my definition of closures is slightly off.  However, the message I want to convey is still the same: closures don&#8217;t matter except under specific circumstances.</strong> </p>
<h2>Definitions</h2>
<p>A closure is what <em>happens when</em> you&#8217;ve made a function&#8217;s private variables (and/or embedded functions) available to outside code.  That&#8217;s it.  There&#8217;s no specific pattern you need to use, it just happens.  That said, there are lots of patterns that take advantage of closures.</p>
<p>IIFEs are simply a way to create a private set of variables and functions.  You create an IIFE by constructing a function expression that contains some private variables and/or embedded functions &#8212; and then executing it. Immediately.  Most meaningful IIFEs create a closure, but they don&#8217;t have to.</p>
<p><strong>Stop</strong>.  Not bad.  Only four tweets-worth.</p>
<h2>Examples</h2>
<p>Let&#8217;s take a look at a few examples.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// safeSnapshot returns a function that filters out </span>
<span style="color: #006600; font-style: italic;">// embarrassing tweets. tweets are only filtered</span>
<span style="color: #006600; font-style: italic;">// when needed, potentially saving cpu time if they </span>
<span style="color: #006600; font-style: italic;">// are never needed.</span>
<span style="color: #003366; font-weight: bold;">function</span> safeSnapshot <span style="color: #009900;">&#40;</span>tweets<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> snapshot <span style="color: #339933;">=</span> tweets.<span style="color: #660066;">slice</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// shallow copy</span>
    <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> safelist <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> len <span style="color: #339933;">=</span> snapshot.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> len<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>snapshot<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span>.<span style="color: #660066;">text</span>.<span style="color: #660066;">indexOf</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#poopin'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&lt;</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                safelist.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>snapshot<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000066; font-weight: bold;">return</span> safelist<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// ... later in the code, we give an object (tweetConsumer) </span>
<span style="color: #006600; font-style: italic;">// a handle to a function that it may use to get tweets </span>
<span style="color: #006600; font-style: italic;">// (via its tweetFetcher property).</span>
<span style="color: #006600; font-style: italic;">// It may or may not ever call this function, but it has it in</span>
<span style="color: #006600; font-style: italic;">// advance.  (Use your imagination to dream up a reason</span>
<span style="color: #006600; font-style: italic;">// this could be useful.  There are many.)</span>
<span style="color: #006600; font-style: italic;">// allTheTweets is just an array of tweets we got from </span>
<span style="color: #006600; font-style: italic;">// somewhere else. (Again, use your imagination. I know</span>
<span style="color: #006600; font-style: italic;">// you have one.)</span>
tweetConsumer.<span style="color: #660066;">tweetFetcher</span> <span style="color: #339933;">=</span> safeSnapshot<span style="color: #009900;">&#40;</span>allTheTweets<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>When <code>safeSnaphot</code> is invoked, it returns a function.  The returned function creates a closure around <code>safeSnapshot</code>&#8216;s local variables because the returned function uses the variables internally (actually it just uses <code>snapshot</code>).  The values (or references) held by these variables will stay in memory as long as something is holding a reference to the returned function.  </p>
<p>At the end of that example, we see that we&#8217;ve handed a reference to the returned function to <code>tweetConsumer</code> as its <code>tweetFetcher</code> property.  As long as <code>tweetConsumer</code> exists and nothing has reassigned its <code>tweetFetcher</code> property, the snapshot array will continue to exist in memory, waiting forever, if necessary, or until Chrome crashes. (<em>omg shaddap! IE-bashing is so 2010 ya know</em>)</p>
<p>Code snippet #2:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> squashed <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>doc<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> nodes<span style="color: #339933;">,</span> howMany <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span>
    <span style="color: #006600; font-style: italic;">// find all links that open another friggin tab</span>
    nodes <span style="color: #339933;">=</span> doc.<span style="color: #660066;">getElementsByTagName</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'a'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> len <span style="color: #339933;">=</span> nodes.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> len<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>nodes<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span>.<span style="color: #660066;">target</span> <span style="color: #339933;">!=</span> <span style="color: #3366CC;">''</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #006600; font-style: italic;">// heh. this'll fix em. oh yeah! dom0 is so hawt.</span>
            nodes<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span>.<span style="color: #660066;">onclick</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
            howMany<span style="color: #339933;">++;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000066; font-weight: bold;">return</span> howMany<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Here&#8217;s a useful IIFE.  It&#8217;s definitely a function expression since we&#8217;re using it inside an expression.  It&#8217;s also being invoked immediately (see last line).  </p>
<p>This is not a closure though.  Why?  Simple: there&#8217;s nothing capturing local variables or embedded functions.  The local variables, <code>nodes</code> and <code>howMany</code>, are only used internally and there are no functions being returned to outside code.</p>
<blockquote><p>What about the variable, howMany?  It&#8217;s being returned!</p></blockquote>
<p>No. I&#8217;ts not.  It&#8217;s <em>value</em> is.  <code>howMany</code>&#8216;s value is being returned and placed in the [outer] variable, <code>squashed</code>.</p>
<blockquote><p>What about the onclick function?</p></blockquote>
<p>The onclick function would create a closure if it referenced variables in its scope, but it doesn&#8217;t.</p>
<h2>What&#8217;s it all mean?</h2>
<p>IIFEs are a useful construct.  They&#8217;re a great way to isolate variables (and can also be used to capture copies of transient variables, but that&#8217;s too tl;dr for this discussion).  IIFEs can also create closures.  In fact, any function can create a closure if it returns a function &#8212; directly or indirectly &#8212; and uses local variables. </p>
<p>Closures are also very useful, but you don&#8217;t create closures via an explicit pattern.  <strong><em>Closures just happen</em></strong> under the right circumstances and are used in many different patterns.</p>
<h2>Note to javascript zealots and trolls</h2>
<p>Yes, I know I skirted around a ton of details.  And, yes, the terminology I used does not accurately reflect the state of the machinery <em>under the hood</em>.  I did it to try to simplify the concepts.  I think I portrayed closures accurately despite the simpler terms.</p>
<p>I also skipped dozens and dozens of great use cases.  If people want to see more use cases, they can <a href="http://lmgtfy.com/?q=javascript+closure+example">google it</a>. </p>
<p>That said, if you&#8217;ve got a useful resource (link) or some additional info you think could be useful to devs who are learning about closures, please leave a comment.  </p>
<p>&#8211; John</p>
<hr/>
<strong>[update 2011-10-03]</strong></p>
<p><strong>I guess I inadvertently hijacked somebody else&#8217;s <a href="http://blog.morrisjohns.com/javascript_closures_for_dummies">blog title</a>.  Although, this person is misusing the term &#8220;closure&#8221;, too.</p>
<p>I also got some twitter-lashing from some very smart people in response to this blog post.  Furthermore, it seems just about every article on the web claims that simply placing a function inside of another function creates a closure.  However, they are all wrong.  Read on:</strong></p>
<h3>Read my lips!</h3>
<blockquote><p>The closure doesn&#8217;t exist until the local scope is <em>externalized</em>.</p></blockquote>
<p>Read that again.  This is the essence of the problem.  A closure happens at run time under certain circumstances.  It&#8217;s not something you construct at design time.</p>
<p>Here&#8217;s yet another example to show what this means:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> practicePhrase<span style="color: #339933;">,</span> practiceCount<span style="color: #339933;">;</span>
    practicePhrase <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;Park the car in Harvard yard.&quot;</span><span style="color: #339933;">;</span>
    practiceCount <span style="color: #339933;">=</span> <span style="color: #CC0000;">10</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #003366; font-weight: bold;">function</span> repeat <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>practicePhrase<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">--</span>practiceCount <span style="color: #339933;">&gt;=</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span> setTimeout<span style="color: #009900;">&#40;</span>repeat<span style="color: #339933;">,</span> <span style="color: #CC0000;">1000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">// this is the important part. pay attention. :)</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">getDay</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!=</span> <span style="color: #CC0000;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        setTimeout<span style="color: #009900;">&#40;</span>repeat<span style="color: #339933;">,</span> <span style="color: #CC0000;">1000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>In this example, we&#8217;re using <code>setTimeout</code> to &#8220;externalize&#8221; the local variables, <code>practicePhrase</code> and <code>practiceCount</code>.  <code>setTimeout</code> doesn&#8217;t externalize in the usual way.  We&#8217;re not returning a function to other javascript somewhere.  Instead, we&#8217;re returning a function to the browser&#8217;s event queue mechanism.  It works the same way, though.</p>
<p>Well, if you fully grokked this example, you&#8217;ll notice that the <code>setTimeout</code> sequence (which executes 10 times) is only initiated <em>if this isn&#8217;t Tuesday</em>.  This means that the example code does not create a closure on Tuesdays.</p>
<p>Why?  Because on Tuesdays, the repeat function &#8212; the one that would create the closure &#8212; is never externalized.</p>
<p>Simply placing a function inside of another function does <strong><em>not</em></strong> create a closure.  It&#8217;s just an instance of <em>function scope</em>, which just means that functions can access variables in enclosing functions.</p>
<p>Some tl;dr articles that got it right:</p>
<p><a href="https://developer.mozilla.org/en/JavaScript/Guide/Closures">MDN &#8211; Closures</a> (a bit of confusion by the author, but read carefully)<br />
<a href="http://en.wikipedia.org/wiki/Closure_(computer_science)">Closure</a> (wikipedia)</p>
<p>And now, I fear, this article is tl;dr, too. </p>
<p>[updated again 2011-10-02] I added some clarification about the function referenced by the onclick handler in the second example. (thx @brianarn!)</p>
]]></content:encoded>
			<wfw:commentRss>http://unscriptable.com/2011/10/02/closures-for-dummies-or-why-iife-closure/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>AMD versus CJS. What&#8217;s the best format?</title>
		<link>http://unscriptable.com/2011/09/30/amd-versus-cjs-whats-the-best-format/</link>
		<comments>http://unscriptable.com/2011/09/30/amd-versus-cjs-whats-the-best-format/#comments</comments>
		<pubDate>Sat, 01 Oct 2011 04:46:23 +0000</pubDate>
		<dc:creator>John Hann</dc:creator>
				<category><![CDATA[AMD]]></category>
		<category><![CDATA[CommonJS]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://unscriptable.com/?p=778</guid>
		<description><![CDATA[JavaScript Harmony will introduce native modules into JavaScript.  Finally.  And when IE9 finally dies a slow death, we'll be able to use native modules in the browser.  In the mean time, there are two competing standards for modules: AMD and CJS Modules 1.1.1.  Which one is better?  Which one should you be using?]]></description>
				<content:encoded><![CDATA[<p>JavaScript Harmony will introduce native modules into JavaScript.  Finally.  And when IE9 finally dies a slow death, we&#8217;ll be able to use native modules in the browser.  <em>Yay corporate support contracts.</em>  In the mean time, there are two competing standards for modules: AMD and CJS Modules 1.1.1.  Which one is better?  Which one should you be using?</p>
<p>I&#8217;ve got an opinion and it may surprise you.</p>
<p><span id="more-778"></span></p>
<h2>What&#8217;s the difference?</h2>
<p>If you&#8217;re not aware of either format, I suggest you start by reading about <a href="https://github.com/amdjs/amdjs-api/wiki">Asynchronous Module Definition</a> and <a href="http://wiki.commonjs.org/wiki/Modules/1.1">CommonJS Modules 1.1</a>.</p>
<p>In a nutshell, AMD is designed for browser environments and CommonJS is targeted at server-side environments.  This fundamental difference has deep repercussions on the formats.  Here&#8217;s a brief (and probably incomplete) summary of the differences between these two environments:</p>
<ul>
<li>Scoping</li>
<li>Distance</li>
<li>Asynchrony</li>
</ul>
<h3>Scoping</h3>
<p>JavaScript that runs in the browser has no way to isolate code completely.  Sure, you can put your code in a function so your <code>var</code> statements don&#8217;t leak variables into the global scope, but it&#8217;s easy to make mistakes.  Who hasn&#8217;t done this? </p>
<p><code>var a = b = 0;</code></p>
<p>AMD can&#8217;t efficiently solve this problem, so it doesn&#8217;t.  Instead, it encourages local scoping by bringing external resources into a local function scope.  </p>
<p>CJS arose from server-side environments, such as node, that started with a clean slate.  In these environments, there is no global scope.</p>
<h3>Distance</h3>
<p>In the browser, most resources are remote, on  a server somewhere.  If you&#8217;re lucky, your resources are cached.  Regardless, it can take time to fetch a resource.  If your code depends on a function in another file, you can&#8217;t know for sure if it&#8217;s already loaded or if it may take a few seconds to arrive.  You can&#8217;t write &#8220;normal&#8221; code if you don&#8217;t know if the function is defined yet!</p>
<p>CJS gets around this problem by assuming that all resources are local and can be fetched in msec or, more likely, <em>microseconds</em>.</p>
<h3>Asynchrony</h3>
<p>A direct result of the distance issue is the need to run tasks asynchronously.  Browsers run JavaScript in a single thread.  If that thread were to wait for a remote resource to be fetched, nothing else could execute and the browser would appear to be unresponsive to the user.  </p>
<p>We get around this by initiating the fetch and requesting a callback when the resource is ready.  The callback is typically in the form of a function, and is typically called &#8230; wait for it .. a <em>callback function</em>.  (<em>JS devs are so freakin smart I tell you.</em>)</p>
<p>Node encourages asynchrony by emphasizing an event-driven programming model.  However, the node creators punted when designing the API to fetch modules and provided the same stale File I/O APIs for fetching other resources.  Personally, I think it would have strengthened the event-driven philosophy if they extended the event-driven philosophy to modules and file-based resources.  </p>
<p>In a nutshell, CJS fetches module resources synchronously.  I guess they thought it makes sense to not introduce the complexity of asynchrony if resources are only microseconds away.</p>
<h2>A Closer look at the formats</h2>
<p>So how do the rival formats handle their diverse target environments?  Let&#8217;s look at AMD:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// define() is a necessary wrapper.</span>
define<span style="color: #009900;">&#40;</span>
    <span style="color: #006600; font-style: italic;">// dependencies are specified in advance.</span>
    <span style="color: #009900;">&#91;</span><span style="color: #3366CC;">'pkgA/modA'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'pkgA/modB'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'pkgZ/modC'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span>
    <span style="color: #006600; font-style: italic;">// the module is declared within a definition function.</span>
    <span style="color: #006600; font-style: italic;">// dependencies are mapped into function parameters.</span>
    <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>modA<span style="color: #339933;">,</span> modB<span style="color: #339933;">,</span> modC<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #006600; font-style: italic;">// inside here is the module's code.</span>
        <span style="color: #006600; font-style: italic;">// the module is exported to the outside world via the </span>
        <span style="color: #006600; font-style: italic;">// the definition function's returned value.</span>
        <span style="color: #000066; font-weight: bold;">return</span> modC <span style="color: #339933;">?</span> modA <span style="color: #339933;">:</span> modB<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Contrast this with CJS:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// there is no explicit wrapper, we just write the module's code.</span>
<span style="color: #006600; font-style: italic;">// this is not global scope! the scope is limited to this file only.</span>
<span style="color: #006600; font-style: italic;">// &quot;free&quot; variables (`require`, `module`, and `exports`) are </span>
<span style="color: #006600; font-style: italic;">// declared to help us define our module and fetch resources.</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// dependencies are specified as needed</span>
<span style="color: #003366; font-weight: bold;">var</span> modC <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'pkgZ/modC'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// the module is exported by decorating the `exports` free variable.</span>
exports.<span style="color: #660066;">foo</span> <span style="color: #339933;">=</span> modC <span style="color: #339933;">?</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'pkgA/modA'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">:</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'pkgA/modB'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>AMD handles the asynchrony by having us declare our module inside of the definition function.  The definition function is essentially a callback function.  It&#8217;s called when all of our dependencies have been resolved.  Some of these may require fetching.  The execution of our module&#8217;s code is delayed until all of our resources are available.  (Note: you can execute code earlier if you simply place it outside of the <code>define()</code>.)</p>
<p>CJS on the other hand prefers to execute the module code as soon as possible, but load/execute the module dependencies only when needed.  In the sample code above, only one of &#8216;pkgA/modA&#8217; or &#8216;pkgA/modB&#8217; will be loaded and executed.  There&#8217;s an added bonus here!  Our code could be significantly more efficient if the environment doesn&#8217;t have to load and execute all of the modules.  </p>
<p>This is a clear win for CJS!  Or is it?  In the browser, there&#8217;s no way to have it both ways with this syntax.  We&#8217;d either have to fetch the dependency in advance or fetch it synchronously.</p>
<p>(Ha ha! AMD has an solution to this problem that works for many, but not all, use cases.  It&#8217;s called <a href="https://github.com/phiggins42/has.js/">has.js</a> and it has a sister plugin, called &#8220;has!&#8221;. (The exclamation mark is part of the plugin name; I didn&#8217;t append my emotion to it.  Well, it is my emotion, but that&#8217;s not what I meant to convey.  What I mean to say is&#8230; nm. whatevs.))</p>
<p>How about code size?  From the example above, CJS is the winner here, for sure.  &#8230; Or is it?  If you were to execute that code in a browser, you&#8217;d be declaring globals left and right while clobbering variables in every other module.  Clearly, we would need to at least wrap the module in an <a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/">IIFE</a> to prevent the module from running in the global scope.</p>
<p>Also, in the example above, I showed the advantage of delayed execution which allowed me to declare less variables.  If you were to map all of the <code>require()</code>-ed modules to variables (and wrap the module in an IIFE), you&#8217;d end up with nearly the same number of bytes.</p>
<h2>And the winner is&#8230;.</h2>
<p>So, if you asked me which one is the winner, I&#8217;d have to say <em>neither</em>.  To be honest, I plan to use both formats.</p>
<p>AMD has some clear benefits in the browser world.  For a more complete list, check out Miller Medeiros&#8217;s recent <a href="http://blog.millermedeiros.com/2011/09/amd-is-better-for-the-web-than-commonjs-modules/">blog article on why AMD is better</a>.  I couldn&#8217;t say it any better than he did.</p>
<p>On the other hand, CJS advocates will argue that it&#8217;s critical to author modules in a format that doesn&#8217;t cater to the <em>transport</em> (more on this later).  I understand and <em>almost</em> agree with their argument, but this article would be way too tl;dr if I were to extrapolate on that argument.</p>
<p>I&#8217;m guessing that both formats will be around for a long, long time.  So here&#8217;s what I plan to do:</p>
<ol>
<li>write modules that could execute in a server environment in CJS format</li>
<li>write modules that could benefit from AMD&#8217;s browser-friendly features in AMD format</li>
</ol>
<p>Duh.</p>
<h2>One more thing&#8230;</h2>
<p>Did I mention that AMD supports wrapped CJS modules?  If you read the wikis I linked at the top of this article, I wouldn&#8217;t have to tell you that because you&#8217;d already know.  Here&#8217;s what one looks like:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">define<span style="color: #009900;">&#40;</span>
    <span style="color: #009900;">&#91;</span><span style="color: #3366CC;">'pkgA/modA'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'pkgA/modB'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'pkgZ/modC'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'require'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'exports'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'module'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span>
    <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>modA<span style="color: #339933;">,</span> modB<span style="color: #339933;">,</span> modC<span style="color: #339933;">,</span> require<span style="color: #339933;">,</span> exports<span style="color: #339933;">,</span> module<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">var</span> modC <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'pkgZ/modC'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
exports.<span style="color: #660066;">foo</span> <span style="color: #339933;">=</span> modC <span style="color: #339933;">?</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'pkgA/modA'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">:</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'pkgA/modB'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>In this hybrid module, we&#8217;re prefetching modules like AMD, but using <code>require()</code> like an R-Value as in CJS.  Funky!  The <code>require</code> and <code>exports</code> &#8220;free&#8221; variables are brought into the modules using reserved dependency names.  In this hybrid model (using CommonJS-ish terminology) AMD is the <em>transport format</em> and CommonJS is the <em>authoring format</em>.  (Thanks to <a href="http://twitter.com/tobie">@tobie</a> for reminding me of this.  Repeatedly.  The SproutCore guys have also given me a <em>tongue lashing</em> or two.)  </p>
<p><a href="http://requirejs.org">RequireJS</a>&#8216;s companion script, r.js, will generate these wrappers for your CJS modules.</p>
<p>I&#8217;ve been experimenting with a slight variation on this.  It compacts better and executes a bit faster, but munges the transport and authoring formats in the process:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">define<span style="color: #009900;">&#40;</span>
    <span style="color: #009900;">&#91;</span><span style="color: #3366CC;">'pkgA/modA'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'pkgA/modB'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'pkgZ/modC'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'require'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'exports'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'module'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span>
    <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>modA<span style="color: #339933;">,</span> modB<span style="color: #339933;">,</span> modC<span style="color: #339933;">,</span> require<span style="color: #339933;">,</span> exports<span style="color: #339933;">,</span> module<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// ok. this looks funny, but it's much easier and more efficient</span>
<span style="color: #006600; font-style: italic;">// to simply replace require() with a variable name than to figure out</span>
<span style="color: #006600; font-style: italic;">// which variable declarations can be removed and how to do that safely.</span>
<span style="color: #006600; font-style: italic;">// I may experiment some more. : )</span>
<span style="color: #003366; font-weight: bold;">var</span> modC <span style="color: #339933;">=</span> modC<span style="color: #339933;">;</span>
&nbsp;
exports.<span style="color: #660066;">foo</span> <span style="color: #339933;">=</span> modC <span style="color: #339933;">?</span> modA <span style="color: #339933;">:</span> modB<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>winning.</p>
<p><strong>[Update 2011-10-01]</strong></p>
<p>I&#8217;m trying not to wreck a nice ending on this blog post, but I just realized a big mistake on my part. I often get confused between CJS and the latest flavor of node. CJS is missing a very important feature, imho. </p>
<p>With CJS, you cannot have a module that returns a single function or constructor. If we are writing modules as focused and fine-grained as possible, then we should be able to do this!</p>
<p>Node allows us to assign our module to the `module.exports` property. A module that only exports a constructor could then look like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> MyConstructor <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span>
module.<span style="color: #660066;">exports</span> <span style="color: #339933;">=</span> MyConstructor<span style="color: #339933;">;</span></pre></div></div>

<p>CJS needs to add this for ms to be 100% on board. Hm. I guess I&#8217;m not really authoring CJS modules now. They&#8217;re node modules. </p>
]]></content:encoded>
			<wfw:commentRss>http://unscriptable.com/2011/09/30/amd-versus-cjs-whats-the-best-format/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>AMD Module Patterns: Singleton</title>
		<link>http://unscriptable.com/2011/09/22/amd-module-patterns-singleton/</link>
		<comments>http://unscriptable.com/2011/09/22/amd-module-patterns-singleton/#comments</comments>
		<pubDate>Fri, 23 Sep 2011 03:03:09 +0000</pubDate>
		<dc:creator>John Hann</dc:creator>
				<category><![CDATA[AMD]]></category>
		<category><![CDATA[Design patterns]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://unscriptable.com/?p=761</guid>
		<description><![CDATA[This is the first in a series of posts illustrating how common design patterns can be achieved using AMD-style JavaScript modules.  We'll also look at some new patterns that are somewhat unique to AMD, including one that should be called nothing less than the "Alley oop slam dunk"!

Let's start at the basics with the simplest of all design patterns: the Singleton.]]></description>
				<content:encoded><![CDATA[<p><em>This is the first in a series of posts illustrating how common design patterns can be achieved using AMD-style JavaScript modules.  We&#8217;ll also look at some new patterns that are somewhat unique to AMD, including one that should be called nothing less than the &#8220;Alley oop slam dunk&#8221;!</em></p>
<p>No, no, we&#8217;re not going to talk about the &#8220;Alley oop slam dunk&#8221; first!  Let&#8217;s start at the basics with the simplest of all design patterns: the Singleton.</p>
<p><span id="more-761"></span></p>
<h2>Singleton</h2>
<p><a href="http://unscriptable.com/code/AMD%2Dmodule%2Dpatterns/#12"><img alt="" src="http://unscriptable.com/code/AMD%2Dmodule%2Dpatterns/images/IMG_6975.jpg" title="Singleton dojo mini" class="alignright" width="50%" /></a></p>
<blockquote><p>The singleton pattern is a design pattern used to [...] restrict the instantiation of a class to one object.</p></blockquote>
<p> &#8212; <a href="http://en.wikipedia.org/wiki/Singleton_pattern">Wikipedia</a></p>
<p>Yah, well that&#8217;s the formal definition.  In classical OO languages maybe you need a pattern for that.  In javascript we have object literals.  There&#8217;s no need to restrict anything.  It&#8217;s as simple as this:</p>
<p><em>(If you&#8217;re new to AMD, stop here and review this <a href="http://unscriptable.com/code/Using-AMD-loaders">intro</a> now.)</em></p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// simple module with no dependencies and no supporting code</span>
define<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
    format<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>dicomDate<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span>dicomDate <span style="color: #339933;">||</span> <span style="color: #3366CC;">''</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">replace</span><span style="color: #009900;">&#40;</span><span style="color: #009966; font-style: italic;">/(?:d{4})d{2}/</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'$1/'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This is just shorthand for the slightly more verbose version:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// simple module with no dependencies and no supporting code</span>
define<span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#123;</span>
        format<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>dicomDate<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span>dicomDate <span style="color: #339933;">||</span> <span style="color: #3366CC;">''</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">replace</span><span style="color: #009900;">&#40;</span><span style="color: #009966; font-style: italic;">/(?:d{4})d{2}/</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'$1/'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>In fact, most AMD loaders probably insert a <a href="http://unscriptable.com/code/Using-AMD-loaders/#23" title="link to intro slide describing definition function">definition function</a> automatically.</p>
<p>Since AMD only executes the definition function once, we&#8217;ve essentially created a singleton.  In the classical sense, a singleton is a class with instance data and state, but we&#8217;re stretching the definition a bit.  Why?  <em>Because this ain&#8217;t Java! <img src='http://unscriptable.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </em>  </p>
<p>Here&#8217;s an example that&#8217;s more like the classical singleton pattern or all the Java wannabees:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">define<span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> instance<span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// look ma! no globals!</span>
    <span style="color: #003366; font-weight: bold;">function</span> Singleton <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">defaultDate</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">''</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    Singleton.<span style="color: #660066;">prototype</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
        format<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>dicomDate<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span>dicomDate <span style="color: #339933;">||</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">defaultDate</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">replace</span><span style="color: #009900;">&#40;</span><span style="color: #009966; font-style: italic;">/(?:d{4})d{2}/</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'$1/'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
        setDefault<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>dateString<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">defaultDate</span> <span style="color: #339933;">=</span> dateString<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">function</span> getSingleton <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span>instance <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>instance <span style="color: #339933;">||</span> <span style="color: #003366; font-weight: bold;">new</span> Singleton<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<h2>Return something!</h2>
<p>The most important thing to remember when creating AMD modules is to <strong>RETURN SOMETHING! RETURN ANYTHING!</strong></p>
<p>Whatever you return from the definition function is what other modules will receive when they request your module.</p>
<p>If you return an object, other modules will receive an object.</p>
<p>If you return a function, other modules will receive a function.</p>
<p>If you return a constructor, other modules will receive a constructor.</p>
<p>If you return a string&#8230; can you guess what&#8217;s gonna happen?  Well, you probably guessed wrong.  Unfortunately, some AMD loaders and compilers/optimizers don&#8217;t handle this case as you&#8217;d expect.  They assume that a string in the first parameter position is a module id and will either return <code>undefined</code> or throw an exception.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// not all builders support a string singleton because</span>
<span style="color: #006600; font-style: italic;">// a string looks like a module id.</span>
define<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;WTF, AMD build tool. I am not a module id!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This is ok, thought, right?  Who is going to have a module that consists of a single string?  </p>
<p>Hmmm&#8230;. what if your module is an HTML template?  The bottom line is that you should be able to return <strong><em>anything</em></strong>.  <a href="http://github.com/unscriptable/curl">curl.js</a> and <a href="http://github.com/unscriptable/cram">cram</a> don&#8217;t restrict the return type of the module since they inspect the parameters from back to front.  The last parameter is always the module definition!  </p>
<p>However, there&#8217;s another solution for loading large text strings: the &#8220;text!&#8221; <a href="http://unscriptable.com/code/AMD%2Dmodule%2Dpatterns/#11">plugin</a>.  You should consider using the text! plugin rather than wrapping the string in a <code>define()</code>.  </p>
<p>But guess what, the text! plugin uses XHR, and XHR doesn&#8217;t work cross-domain in legacy browsers.  For cross-domain text resources, you can use <a href="http://en.wikipedia.org/wiki/JSONP">JSONP</a> instead.  JSONP is pretty darn easy to implement using AMD:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// a module to convert some jsonp-based resources to AMD:</span>
define<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span><span style="color: #3366CC;">'require'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'mylib/Deferred'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>req<span style="color: #339933;">,</span> Deferred<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> promise <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Deferred<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    req<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span><span style="color: #3366CC;">'cdnlib/template?jsonp=define'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'cdnlib/data?jsonp=define'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span>
        <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>template<span style="color: #339933;">,</span> data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            promise.<span style="color: #660066;">resolve</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span> template<span style="color: #339933;">:</span> template<span style="color: #339933;">,</span> data<span style="color: #339933;">:</span> data <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">return</span> promise<span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// could also use a callback function</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>By telling the JSONP service that our callback is named &#8220;define&#8221; (<code>?jsonp=define</code>), we can simply use the built-in AMD async <a href="http://unscriptable.com/code/Using-AMD-loaders/#28">require mechanism</a> to fetch the resources from the cross-domain server.  I used a promise in this example just because I like promises, but you could devise a different implementation using a callback function, of course.</p>
<p>Here&#8217;s what those resources would look like when they&#8217;re returned:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// cdnlib/template will return something like:</span>
define<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'&lt;div dojotype=&quot;dijit.form.Form&quot;&gt;...&lt;/div&gt;'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// cdnlib/data will return something like:</span>
define<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span> test<span style="color: #339933;">:</span> <span style="color: #3366CC;">'bostonian'</span><span style="color: #339933;">,</span> question<span style="color: #339933;">:</span> <span style="color: #3366CC;">'wicked?'</span><span style="color: #339933;">,</span> answer<span style="color: #339933;">:</span> <span style="color: #3366CC;">'pissah!'</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Magic!</p>
<p>Next, we&#8217;ll look at the Decorator pattern.</p>
<p>Comments welcome!</p>
<p>&#8211; John</p>
]]></content:encoded>
			<wfw:commentRss>http://unscriptable.com/2011/09/22/amd-module-patterns-singleton/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The first annual dojoconf!</title>
		<link>http://unscriptable.com/2011/09/22/the-first-annual-dojoconf/</link>
		<comments>http://unscriptable.com/2011/09/22/the-first-annual-dojoconf/#comments</comments>
		<pubDate>Thu, 22 Sep 2011 11:46:06 +0000</pubDate>
		<dc:creator>John Hann</dc:creator>
				<category><![CDATA[AMD]]></category>
		<category><![CDATA[dojo]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://unscriptable.com/?p=751</guid>
		<description><![CDATA[I just got back from the first ever dojoconf in Washington DC. I asked Dylan and Chris if they were planning to do it annually and I got something equivalent to &#8220;F**K YEAH!&#8221; Good. cuz it was awesome. I was honored to present about AMD Module Patterns at dojoconf. My slides are here. A half [...]]]></description>
				<content:encoded><![CDATA[<p>I just got back from the first ever <a href="http://dojoconf.com/">dojoconf</a> in Washington DC.  I asked <a href="http://twitter.com/dylans">Dylan</a> and <a href="http://twitter.com/voodootikigod">Chris</a> if they were planning to do it annually and I got something equivalent to &#8220;F**K YEAH!&#8221;</p>
<p>Good. cuz it was awesome.  <img src='http://unscriptable.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>I was honored to present about <a href="http://unscriptable.com/code/AMD-module-patterns/">AMD Module Patterns</a> at dojoconf.  My slides are <a href="http://unscriptable.com/code/AMD-module-patterns/">here</a>.  A half hour is not nearly enough time to present on even a couple of patterns.  It didn&#8217;t help that I was high on cold medication, so I think I missed half of the points I wanted to make and missed half my slides at the same time.  <img src='http://unscriptable.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<p>To rectify the situation, I will write a blog post on each pattern.  My goal is to write about one pattern a day until they&#8217;re all done.  Wish me luck. <img src='http://unscriptable.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>&#8211; John</p>
<p>P.S. This was my first time representing a corporation at a conference.  I have been a full-time employee at <a href="http://lifeimage.com/">lifeIMAGE</a> in Newton, MA since August 2010.  lifeIMAGE sponsored the Hacker Lounge at dojoconf and paid for the awesome <a href="http://unscriptable.com/code/AMD%2Dmodule%2Dpatterns/images/IMG_6958.JPG">dojo minis</a>!  (Btw, we&#8217;re always hiring javascript engineers!)</p>
]]></content:encoded>
			<wfw:commentRss>http://unscriptable.com/2011/09/22/the-first-annual-dojoconf/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What is the fastest way to load AMD modules?</title>
		<link>http://unscriptable.com/2011/09/21/what-is-the-fastest-way-to-load-amd-modules/</link>
		<comments>http://unscriptable.com/2011/09/21/what-is-the-fastest-way-to-load-amd-modules/#comments</comments>
		<pubDate>Thu, 22 Sep 2011 03:13:44 +0000</pubDate>
		<dc:creator>John Hann</dc:creator>
				<category><![CDATA[AMD]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://unscriptable.com/?p=735</guid>
		<description><![CDATA[The AMD format for JavaScript modules was created to allow devs to write elegant, modular code rather than the silly global, name-spaced hackfest we've been writing.  However, AMD has a hidden benefit: it allows modules to be downloaded in parallel, rather than sequentially.  This is a potentially huge performance win.  

However, does this really matter for production code?]]></description>
				<content:encoded><![CDATA[<p>The AMD format for JavaScript modules was created to allow devs to write elegant, modular code rather than the silly global, name-spaced hackfest we&#8217;ve been writing.  However, AMD has a hidden benefit: it allows modules to be downloaded in parallel, rather than sequentially.  This is a potentially huge performance win.  </p>
<p>However, does this really matter for production code?<br />
<span id="more-735"></span></p>
<h2>Blocking before Loading</h2>
<p>Virtually all of the examples of AMD code out on the web look something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;script src=&quot;some-amd-loader.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
someAmdLoader([&quot;moduleA&quot;, &quot;moduleB&quot;, &quot;domReady!&quot;], function (A, B) {
    var app = new A(), boot = new B(app);
    boot.init();
});
&lt;/script&gt;</pre></div></div>

<p>In this example, we&#8217;re loading moduleA and moduleB in parallel.  This is the fast way to do it, right?  Yes, but also note that we&#8217;re loading some-amd-loader.js in a blocking fashion.  The second script element (and the rest of the document) has to wait for some-amd-loader.js to finish loading and executing before proceeding.</p>
<p>This isn&#8217;t ideal, of course.  So how do we fix this?</p>
<p>Answer: by only including one script element in the page and ensuring that that single script allows the page to continue parsing and rendering.</p>
<h2>Native async loading</h2>
<p>Here&#8217;s what we really want:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;script src=&quot;myapp-bootstrap.js&quot; defer async=&quot;true&quot;&gt;&lt;/script&gt;</pre></div></div>

<p>Newer browsers support the async attribute.  <code>async="true"</code> instructs the browser that it can proceed to parse and evaluate any future script elements without waiting.  You&#8217;d think a browser would notice that there&#8217;s only one script element, right?  Just in case, we&#8217;re going to tell it how we want it to behave. <img src='http://unscriptable.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Older browsers don&#8217;t support the async attribute.  However, they do support the defer attribute.  This attribute tells the browser that it may defer execution of the script until a convenient time &#8212; even after the body is rendered.  Unfortunately, browsers don&#8217;t all act the same with this attribute.  Most browsers, though, do a fairly good job when there&#8217;s only one script element in the document.</p>
<p>Since the browser isn&#8217;t waiting for the script&#8217;s javascript to load or execute, the script element can be in the head where it belongs.  There is no need to put it at the ned of the body element.  </p>
<p>So, what&#8217;s myapp-bootstrap.js look like in this scenario?  The sky&#8217;s the limit, but you can imagine a minimal set of requirements:</p>
<p>1. it contains an AMD loader<br />
2. it contains one of the following:<br />
    a. instructions to load the rest of the app<br />
    b. the actual code for the rest of the app</p>
<p>If you&#8217;re compiling/optimizing your AMD modules into a single js file already, it&#8217;s not too much harder to concatenate the actual AMD loader onto the front of the file (using requirements 1 and 2b above).  Some compilers/optimizers have support for this built in, <a href="http://requirejs.org">RequireJS</a>, for example.  RequireJS also has a companion loader, <a href="http://github.com/jrburke/almond">almond</a>, that is tiny and can handle the simpler environment inside a compiled file.</p>
<p>So, essentially, all that AMD provided for us in this single-script scenario is a way to ensure ordering of our modules into a single file, it seems.  Does this mean that the whole async loading behavior we&#8217;ve been touting about AMD is just a bunch of &#8220;<a href="http://github.com/paulirish/html5-boilerplate/issues/28#issuecomment-1773156">snake oil</a>&#8220;?  Not at all.  Keep reading:</p>
<h2>We ain&#8217;t oiling no snakes</h2>
<p>Let&#8217;s say our web app has several pages.  Each of these pages has a core set of modules it requires to function and a set of modules that are unique to it.  This is not an unlikely scenario, and is quite likely the most common case.  </p>
<p>In this scenario, it could be ideal to allow the common core modules to be fetched from cache and the unique, page-specific modules to be loaded separately.  Each subsequent page load would be fast because it&#8217;s not loading as much code.  For this scenario, requirements 1 and 2a are the best choice.  The code inside the single file would look a lot like the original code snippet above:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// loader source code goes here</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// initialize our app in two parts!</span>
someAmdLoader<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span><span style="color: #3366CC;">&quot;moduleA&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;moduleB&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;domReady!&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>A<span style="color: #339933;">,</span> B<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> app <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> A<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> boot <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> B<span style="color: #009900;">&#40;</span>app<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    boot.<span style="color: #660066;">init</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>How finely grained you break up your app is totally unique to your app and your target browsers.  If you are targeting older IE&#8217;s, then your app is burdened by limited HTTP requests.  A small number of fetches per page is best.  </p>
<p>More sophisticated apps or ones that can ignore older browsers may be able to take advantage of multiple parallel downloads.  However, you must remember that each image, css file, and xhr consumes an HTTP request!</p>
<p>Most of the apps I write have a very sparse body because the UI is built by templates embedded in the javascript.  The css is embedded, too (via <a href="http://github.com/unscriptable/curl">curl.js</a>&#8216;s css! plugin and the <a href="http://github.com/unscriptable/cram">cram</a> optimization tool).  This means we can break the app up into several files.  Some of these files are loaded when the page loads.  Others are loaded when needed (&#8220;lazily&#8221;).</p>
<p>Do some experimentation to figure out what your ideal situation is.  If you already have, please share it with the rest of us in the comments section!  There are other ways we could load modules since AMD is very flexible.  Do you have an entirely different approach?  </p>
<p>Thanks!</p>
<p>&#8211; John</p>
<p><strong>[update 2011-09-22 12:35 PM EDT]</strong> @getify says that he doesn&#8217;t recommend the &#8220;defer&#8221; attribute due to jQuery/FF3.x issues. see twitter convo <a href="http://twitter.com/getify/status/116879861175422976">here</a>.  Also: &#8220;defer&#8221; isn&#8217;t always what you want.  Use wisely. <img src='http://unscriptable.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://unscriptable.com/2011/09/21/what-is-the-fastest-way-to-load-amd-modules/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Modules &gt; Frameworks</title>
		<link>http://unscriptable.com/2011/05/02/modules-frameworks/</link>
		<comments>http://unscriptable.com/2011/05/02/modules-frameworks/#comments</comments>
		<pubDate>Mon, 02 May 2011 19:16:37 +0000</pubDate>
		<dc:creator>John Hann</dc:creator>
				<category><![CDATA[AMD]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://unscriptable.com/?p=729</guid>
		<description><![CDATA[My slides from JSCONF 2011 in Portland, May 1: http://unscriptable.com/code/Modules-Frameworks/ Feedback appreciated!]]></description>
				<content:encoded><![CDATA[<p>My slides from JSCONF 2011 in Portland, May 1: <a href="http://unscriptable.com/code/Modules-Frameworks/">http://unscriptable.com/code/Modules-Frameworks/</a></p>
<p>Feedback appreciated!</p>
]]></content:encoded>
			<wfw:commentRss>http://unscriptable.com/2011/05/02/modules-frameworks/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using AMD loaders to write and manage modular javascript</title>
		<link>http://unscriptable.com/2011/04/27/using-amd-loaders-to-write-and-manage-modular-javascript/</link>
		<comments>http://unscriptable.com/2011/04/27/using-amd-loaders-to-write-and-manage-modular-javascript/#comments</comments>
		<pubDate>Thu, 28 Apr 2011 01:24:24 +0000</pubDate>
		<dc:creator>John Hann</dc:creator>
				<category><![CDATA[AMD]]></category>
		<category><![CDATA[cujo.js]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://unscriptable.com/?p=719</guid>
		<description><![CDATA[<a href="http://unscriptable.com/code/Using-AMD-loaders/">http://unscriptable.com/code/Using-AMD-loaders/</a>]]></description>
				<content:encoded><![CDATA[<p>Recently, I gave a short presentation about AMD (Asynchronous Module Definition) at the Boston JavaScript Meetup Group.  Here are the slides:</p>
<p><a href="http://unscriptable.com/code/Using-AMD-loaders/">http://unscriptable.com/code/Using-AMD-loaders/</a></p>
<p>There wasn&#8217;t enough time to talk about all of the AMD loaders in existence, and certainly not enough time to dig into the many use cases and nuances of AMD-formatted modules.  However, I hope I was able to help improve awareness of AMD and javascript modules in general.</p>
<p>Enjoy!</p>
<p><strong>[Update 2011-04-27]</strong> If you&#8217;re wondering what happened to the &#8220;manage&#8221; part of the title&#8217;s &#8220;write and manage&#8221;&#8230; it&#8217;s coming in a future presentation. <img src='http://unscriptable.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://unscriptable.com/2011/04/27/using-amd-loaders-to-write-and-manage-modular-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>curl.js &#8211; yet another AMD loader [updated]</title>
		<link>http://unscriptable.com/2011/03/30/curl-js-yet-another-amd-loader/</link>
		<comments>http://unscriptable.com/2011/03/30/curl-js-yet-another-amd-loader/#comments</comments>
		<pubDate>Thu, 31 Mar 2011 01:24:33 +0000</pubDate>
		<dc:creator>John Hann</dc:creator>
				<category><![CDATA[AMD]]></category>
		<category><![CDATA[cujo.js]]></category>
		<category><![CDATA[i18n]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[l10n]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://unscriptable.com/?p=698</guid>
		<description><![CDATA[Over the past several weeks, I&#8217;ve been writing an AMD-compatible javascript loader called curl.js. AMD stands for Asynchronous Module Definition and is a CommonJS proposed standard for writing javascript modules. The module format closely follows the proposed migration path set out by ECMA&#8217;s proposed ES-Harmony javascript modules. curl stands for Cujo Resource Loader since it&#8217;s [...]]]></description>
				<content:encoded><![CDATA[<p>Over the past several weeks, I&#8217;ve been writing an AMD-compatible javascript loader called <a href="https://github.com/unscriptable/curl">curl.js</a>. AMD stands for Asynchronous Module Definition and is a <a href="http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition">CommonJS proposed standard</a> for writing javascript modules.  The module format closely follows the <a href="http://wiki.ecmascript.org/doku.php?id=harmony:modules">proposed migration path</a> set out by ECMA&#8217;s proposed ES-Harmony javascript modules.</p>
<p>curl stands for <em>Cu</em>jo <em>R</em>esource <em>L</em>oader since it&#8217;s an integral part of the re-engineering of <a href="http://cujojs.com">cujo.js</a>.</p>
<p>An AMD-compatible javascript loader is (surprise, surprise) an asynchronous javascript loader that is savvy about AMD-formatted javascript modules.</p>
<p><strong>[update]</strong><br />
Version 0.3.2 is out! <a href="https://github.com/unscriptable/curl">fork it!</a></p>
<p><span id="more-823"></span></p>
<h1>What is an asynchronous loader?</h1>
<p>Web apps, especially large ones, require many modules and resources. Most of these modules and resources need to be loaded at page load, but some may be loaded later, either in the background or &#8220;just in time&#8221;. They also need to be loaded as quickly as possible.</p>
<p>The traditional way to load javascript modules is via a <code>&lt;SCRIPT&gt;</code> element in an HTML page. Similarly, CSS files are loaded via a <code>&lt;LINK&gt;</code> element, and text resources are either loaded in the page or via XHR calls.</p>
<p>The problem with <code>&lt;SCRIPT&gt;</code> and <code>&lt;LINK&gt;</code> elements is that a browser must execute them sequentially since it has no idea if one may depend on another. It just assumes the developer has placed them in the correct order and that there are dependencies. (The term &#8220;synchronous loading&#8221; is used to describe this process since the elements are executed in a single timeline. I think &#8220;sequential&#8221; is a much better word, but nobody asked me.)</p>
<p>If there are no dependencies between two files, loading them sequentially is a waste of time. These files could be loaded and executed in parallel (i.e at the same time).</p>
<p>An asynchronous loader does just that: it loads javascript files (and other types of files) in parallel as much as possible.</p>
<p>curl.js has lots of company. Other async loaders include LABjs, Steal.js, yepnope.js, $script.js, bdLoad, and RequireJS.</p>
<p>(<a href="https://spreadsheets.google.com/ccc?key=0Aqln2akPWiMIdERkY3J2OXdOUVJDTkNSQ2ZsV3hoWVE&amp;hl=en#gid=2">a more complete list can be found here</a>)</p>
<h1>What is AMD?</h1>
<p>Asynchronous Module Definition is the CommonJS proposed standard for javascript modules that can be loaded by asynchronous loaders. It defines a simple API that developers can use to write their javascript modules so that they may be loaded by any AMD-compliant loader.</p>
<p>The AMD proposal follows the <a href="http://wiki.commonjs.org/wiki/Modules/1.1">CommonJS Modules proposal</a> as much as possible. Because of the way browsers load and evaluate scripts, AMD can&#8217;t follow it completely without causing significant processing overhead (think serious regex action and eval()). Instead, AMD allows us to place a lightweight wrapper around javascript modules to help work around the shortcomings.</p>
<p>Ultimately, both proposals (AMD and Modules 1.1) are in preparation for an official javascript modules specification and eventual implementation in browsers. (Hopefully!)</p>
<p>If you don&#8217;t want to wait for official javascript modules, then don&#8217;t. The future is now. AMD works now &#8212; and it&#8217;s awesome.</p>
<p>AMD&#8217;s API focuses on two globally-available functions: <code>require()</code> and <code>define()</code>. <code>require()</code> specifies a list of dependent modules or resources that must be loaded before running a set of code. This code resides in a callback function that is executed asynchronously, i.e. it runs later, not in the current &#8220;thread&#8221;. Specifically, it executes when all of the dependencies are loaded and ready.</p>
<p>Actually, the proposal says that the <code>require()</code> function could have a different name &#8212; or could even be implemented differently. To keep with convention &#8212; and to better integrate with non-AMD CommonJS modules &#8212; we&#8217;re using <code>require()</code>, but <code>curl()</code> is also an alias to <code>require()</code>.</p>
<p>It&#8217;s more important that the <code>define()</code> method be consistent. This is the method that tells the loader what modules have been loaded by a script. <code>define()</code> also specifies a list of dependencies and a callback function that defines and/or creates the resource when the dependencies are ready. Optionally, <code>define()</code> also takes a name parameter, but this is mainly for build tools and optimizers.</p>
<p>AMD&#8217;s API also helps code reuse by providing compatibility with CommonJS server modules. AMD-compliant loaders support the same <code>require()</code> syntax and argument signatures as server-side javascript (ssjs) modules.</p>
<p>Not all async loaders are AMD-compliant. Of the list above, only the following are AMD-compliant:</p>
<p>curl.js <a href="http://github.com/unscriptable/curl">http://github.com/unscriptable/curl</a></p>
<p>RequireJS <a href="http://requirejs.org/">http://requirejs.org/</a></p>
<p>bdLoad <a href="http://bdframework.org/bdLoad">http://bdframework.org/bdLoad</a></p>
<p>(there are a few others in that google spreadsheet link)</p>
<p>The beauty of AMD loaders is their ability to remove the drudgery of manually managing dependencies. Since all dependencies are listed within the modules, the loader will ensure that everything is loaded into the browser &#8212; and in the right order.</p>
<p>Even better: the modules are always loaded in parallel without blocking the loading process of the rest of the page.</p>
<p>Most of the current AMD loaders also support plugins. Plugins allow you to load CSS, HTML templates, i18n/L10n bundles, CSS generated from LESS, plain vanilla javascript files, etc.  Again, these are loaded without blocking so the performance is optimal.</p>
<h1>So how can I get my hands on curl.js?</h1>
<p><a href="https://github.com/unscriptable/curl">curl.js</a> is up on github!  Fork it or clone it to your local disk and check out the Very Simple Example in the README file.  </p>
<p>At the time of this blog post, curl.js is at version 0.3.1 and is not 100% compatible with CommonJS Modules 1.1 (only missing the <code>exports</code> and <code>module</code> parameters).  However, I am currently unit-testing 0.3.2, which is 100% compatible!  </p>
<p>Compared to other AMD loaders, curl.js is <strong>tiny</strong>.  At 4.5KB (2.1KB gzipped using Google Closure Compiler), it&#8217;s half the size of the others.  It also employs some wicked cool techniques using <a href="http://wiki.commonjs.org/wiki/Promises">promises</a>.</p>
<p>Version 0.3.2 will be ready for production use, despite the <em>zero-dot</em> version number.  Please check it out and let me know what you think!</p>
]]></content:encoded>
			<wfw:commentRss>http://unscriptable.com/2011/03/30/curl-js-yet-another-amd-loader/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OOCSS for JavaScript Pirates</title>
		<link>http://unscriptable.com/2010/11/15/oocss-for-javascript-pirates/</link>
		<comments>http://unscriptable.com/2010/11/15/oocss-for-javascript-pirates/#comments</comments>
		<pubDate>Tue, 16 Nov 2010 03:17:52 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Non-programming]]></category>
		<category><![CDATA[OOCSS]]></category>

		<guid isPermaLink="false">http://unscriptable.com/?p=676</guid>
		<description><![CDATA[A few weeks back I had the awesome opportunity to speak at the jQuery Conference in Boston. A colleague, Boaz Sender, encouraged me to propose a topic, but I couldn&#8217;t help wondering, &#8220;What could a dojo enthusiast possibly speak about at a jQuery conference?&#8221; Speak about dojo? Uh, no way. That wouldn&#8217;t fly. How about [...]]]></description>
				<content:encoded><![CDATA[<p>A few weeks back I had the awesome opportunity to speak at the <a href="http://events.jquery.org/2010/boston/">jQuery Conference in Boston</a>.  A colleague, <a href="http://boazsender.com/">Boaz Sender</a>, encouraged me to propose a topic, but I couldn&#8217;t help wondering, &#8220;What could a dojo enthusiast possibly speak about at a jQuery conference?&#8221;  </p>
<p><em>Speak about dojo? Uh, no way. That wouldn&#8217;t fly.</em></p>
<p><em>How about something about pure JavaScript? Maybe I could extract a feature of cujo.js and turn it into a jQuery plugin! &#8230; Nah, that&#8217;ll take too long.  No time.</em></p>
<p><em>Wait! OOCSS! It&#8217;s applicable to all JavaScript development!</em><br />
<span id="more-676"></span></p>
<p><!-- embedded slideshare widget --></p>
<div style="width:425px; float:right; margin-left: 10px;" id="__ss_5465648"><strong style="display:block;margin:12px 0 4px"><a href="http://www.slideshare.net/unscriptable/oocss-for-javascript-pirates-jqcon-boston" title="OOCSS for JavaScript Pirates jQcon Boston">OOCSS for JavaScript Pirates jQcon Boston</a></strong><object id="__sse5465648" width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=oocssforjavascriptpiratespresentationatjqconboston-101017095722-phpapp01&#038;rel=0&#038;stripped_title=oocss-for-javascript-pirates-jqcon-boston&#038;userName=unscriptable" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed name="__sse5465648" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=oocssforjavascriptpiratespresentationatjqconboston-101017095722-phpapp01&#038;rel=0&#038;stripped_title=oocss-for-javascript-pirates-jqcon-boston&#038;userName=unscriptable" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed></object>
<div style="padding:5px 0 12px">View more <a href="http://www.slideshare.net/">presentations</a> from <a href="http://www.slideshare.net/unscriptable">John Hann</a>.</div>
</div>
<p>I knew that topic was the best chance I had &#8212; if a dojo guy had a chance at all &#8212; to speak at a jQuery conference.  But how to sell the idea to jQuery developers?  Most of the JavaScript coders I know either don&#8217;t understand CSS or don&#8217;t care to understand it.  Well, to be fair, that description fits most of the dojo coders I know.  Lots of jQuery devs come from a design background, so they know CSS.  But still&#8230; how to let the conference attendees know that this talk won&#8217;t simply be about the same old CSS concepts?</p>
<p><em>I&#8217;ll have to just tell them it&#8217;s for advanced coders! This is <strong>CSS for JavaScript Pirates!!!</strong></em></p>
<p>There were only a few days left before I had to submit the proposal for the talk, so I did what every over-worked coder does: I waited until the night the proposal was due.  </p>
<p>I did two revisions before calling it good enough.  (I usually like to wait a few days between revisions because it makes it easier for me to judge the content objectively, but that almost never happens.)</p>
<p>At the bottom of my proposal, I added some additional notes:</p>
<blockquote><p>Note to reviewer: It&#8217;s no secret that I&#8217;m a dojo contributor working on a dojo-based MVC framework (cujo.js).  Let it be known that I&#8217;ve also worked on my share of jQuery projects!  (Who hasn&#8217;t?)  This talk is about OOCSS and JavaScript, not cujo.js or dojo.  I will be showing jQuery code snippets and will explain techniques that jQuery devs can use in their current projects.
</p></blockquote>
<p><em>That oughta alleviate any doubters.  I hope.</em></p>
<p>There was still one major problem, though.  I needed a demo.  I could show some code snippets on the screen, but without a real demo, it just wouldn&#8217;t have the same impact.  I thought I&#8217;d have to write one.  But I knew I&#8217;d never make the time and would end up rushing both the presentation and the demo.  That&#8217;d just make for a sucky experience &#8212; and a sucky, stressful week.</p>
<p>Then it dawned on me.  My buddy, <a href="http://blog.briancavalier.com/">Brian</a>, had an awesome demo already!  His <a href="http://briancavalier.com/digital-clock/">CSS3 Digital Clock</a> app would be perfect!  </p>
<p><em>First, let&#8217;s see if I even get picked. </em></p>
<p>Two days later I got the email with the subject line: &#8220;Your jQuery Boston Conference 2010 talk is accepted!&#8221;</p>
<p><em><strong>WOOHOO!!!</strong></em></p>
<p>A couple of emails, chat conversations, and phone calls later Brian was on the speaker list, too!  </p>
<p><em>This is gonna be EPIC!</em></p>
<p>And it was.  I got a bit nervous in the middle and forgot half of what I wanted to say, but I think I got the major points across.  Brian did an amazing demo, and several dozens of people came up to us later and thanked us for the talk.  I guess that means it was a success.  </p>
<p>Kudos to the jQuery team, to the conference organizers, and to the other speakers.  The whole conference was a huge success, imho.  I am quite honored to have been able to participate in such an awesome event.</p>
<p>For more about the presentation and OOCSS, check out some of these links:</p>
<p>Brian debuted the <a href="http://briancavalier.com/digital-clock/explode.html">exploding mod</a> of the digital clock at the show.  (Very cool.)</p>
<p>Brian&#8217;s <a href="http://blog.briancavalier.com/oocss-for-javascript-pirates-at-jqcon-2010">write-up</a> after the event.</p>
<p>Brian, looking more like a <a href="http://photos.brookhartfamily.com/Events/jQuery-Conference-Boston-2010/14226246_2VpfJ#1051103962_WwDrN">GQ model</a>, than a pirate.  </p>
<p>Me, looking <a href="http://photos.brookhartfamily.com/Events/jQuery-Conference-Boston-2010/14226246_2VpfJ#1051103183_kUhYa">rather stressed</a>. I think I was saying &#8220;yarrrrrrrr&#8221;.</p>
<p>Another link to the <a href="http://www.slideshare.net/unscriptable/oocss-for-javascript-pirates-jqcon-boston">slides</a>.</p>
<p><a href="http://speakerrate.com/talks/4642-oocss-for-javascript-pirates">Rate me and Brian</a> if you attended the talk!</p>
<p>The <a href="http://wiki.github.com/stubbornella/oocss/">github repo</a> for OOCSS.</p>
]]></content:encoded>
			<wfw:commentRss>http://unscriptable.com/2010/11/15/oocss-for-javascript-pirates/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>cujo.js — OOJS, OOCSS, and OOHTML — Part 1 (OOCSS for Engineers)</title>
		<link>http://unscriptable.com/2010/08/31/cujo-js-oojs-oocss-and-oohtml-part-1/</link>
		<comments>http://unscriptable.com/2010/08/31/cujo-js-oojs-oocss-and-oohtml-part-1/#comments</comments>
		<pubDate>Tue, 31 Aug 2010 11:47:07 +0000</pubDate>
		<dc:creator>John Hann</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[cujo.js]]></category>
		<category><![CDATA[In-browser MVC]]></category>
		<category><![CDATA[Inheritance]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[OOCSS]]></category>

		<guid isPermaLink="false">http://unscriptable.com/?p=654</guid>
		<description><![CDATA[I've seen several engineer's eyes glaze over when I mention OOCSS, but don't dismiss it as just a rehashed retelling of how to structure your CSS.  OOCSS is a very powerful and efficient tool, especially when used in conjunction with Object-Oriented JavaScript and inheritable HTML templates. ]]></description>
				<content:encoded><![CDATA[<p>One of the coolest concepts in <a href="http://cujojs.com/">cujo.js</a> is the introduction of Object-Oriented CSS into the Views and Widgets.  I&#8217;ve seen several engineer&#8217;s eyes glaze over when I mention OOCSS, but don&#8217;t dismiss it as just a rehashed retelling of how to structure your CSS.  OOCSS is a very powerful and efficient tool, especially when used in conjunction with Object-Oriented JavaScript and inheritable HTML templates.  </p>
<p>I&#8217;d love to dive right in and show you how it all works in cujo.js, but you&#8217;ve got to have a firm understanding of OOCSS for any of it to make sense.  Let&#8217;s get started&#8230;</p>
<p><span id="more-654"></span></p>
<h2 id="basic-principles">Basic principles of OOCSS</h2>
<p>Where better to learn the basic principles of Nicole Sullivan&#8217;s OOCSS than from the <a href="http://wiki.github.com/stubbornella/oocss/">source</a>?  I highly recommend you watch the slideshow and read the FAQ.  Here are some of the main points:</p>
<p>An &#8220;object&#8221; in OOCSS is an HTML fragment and its associated CSS classes*.<br />
You extend objects by applying multiple classes to its root element.<br />
You must follow some basic guidelines:<br />
	Separate structure from skin (styling).<br />
	Separate container from content.<br />
	Don&#8217;t use ID attributes to define CSS rules.<br />
	Use CSS &#8220;hacks&#8221; for targeting and fixing browser quirks.</p>
<p>*Nicole alludes to some JavaScript associated with these OOCSS &#8220;objects&#8221; (a hilariously surprising assessment from the perspective of a JavaScript engineer who might think of JavaScript as the primary language and of CSS as secondary).  </p>
<p>Nicole includes several other guidelines, as well.  All the guidelines can be summarized into three major categories: 1) guidelines to help reuse objects and CSS classes, 2) guidelines to prevent unnecessary specificity increases, and 3) guidelines to allow OOCSS principles to work in ancient browsers.</p>
<p>The ultimate benefit of following OOCSS principles is optimal reuse of CSS rules and OOCSS objects.</p>
<p>For an excellent and detailed example of OOCSS in action (and a very slick use of CSS3), jump over to Brian Cavalier&#8217;s blog post, <a href="http://briancavalier.posterous.com/building-a-digital-clock-with-oocss-and-mvc">Building a digital clock with OOCSS and MVC </a>and come back.  </p>
<h2 id="oocss-inheritance">OOCSS inheritance</h2>
<p>If code reuse were the end of the story about OOCSS, it would certainly be no small achievement, to say the least.  Nicole has done an amazing service to the web industry, especially to those whose main job is to wrangle CSS.  But little did she know, she also planted a seed of inspiration in several JavaScript engineers&#8217; heads, mine included.  I had been already trying to form solid ideas around very similar CSS patterns, but couldn&#8217;t find the right words or evidence.  After watching her speak live at TXJS 2010, things started to become crystal clear &#8212; especially when she started talking about reusable objects.</p>
<p>One of the most common methods to reuse code is through inheritance.  In classical object-oriented languages, classes inherit attributes and behavior from ancestor classes.  The classes are then used to construct objects.  In prototypal languages (such as JavaScript), objects inherit attributes and behavior from ancestor objects.  However, in OOCSS, objects inherit attributes and <em>run-time</em> state from ancestor objects.</p>
<p>Read that one more time: &#8220;&#8230;objects inherit attributes and <em>run-time</em> state&#8230;&#8221;  We&#8217;re not talking about some static, compile-time concept as with classical inheritance.  And we&#8217;re not talking about inheritance that happens during object construction.  We&#8217;re talking about run-time, baby!  </p>
<p>As an object changes at run time from one state to another, so too do it&#8217;s descendants.  Or, conversely, as an object&#8217;s ancestors states change, so too does the object.  Brian and I talked about this concept and dubbed the term, &#8220;whole state&#8221;, to describe the object&#8217;s current state combined with the states of its ancestors.</p>
<p>Let&#8217;s jump right into an example to better grasp this.  Here&#8217;s a simple HTML snippet from a facetious &#8220;club&#8221; project:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;section class=&quot;club-view club-hawt-view&quot;&gt;
    &lt;ul class=&quot;club-list&quot;&gt;
        &lt;li class=&quot;club-item club-rock-item&quot;&gt;1st Item&lt;/li&gt;
        &lt;li class=&quot;club-item club-disco-item&quot;&gt;2nd Item&lt;/li&gt;
        &lt;li class=&quot;club-item club-pop-item&quot;&gt;3rd Item&lt;/li&gt;
    &lt;/ul&gt;
    &lt;button class=&quot;dance-mode-selector&quot;&gt;Let's do Disco!&lt;/button&gt;
&lt;/section&gt;</pre></div></div>

<p>Notice the name-spaced css classes (using dash-notation to be friendly to HTML4 strict documents).  While not important to this discussion, name-spaces are important to protect your code from name conflicts in large projects, especially if not all of the CSS uses OOCSS principles!</p>
<p>More importantly, notice the classes on the root element of our topmost &#8220;object&#8221;.  <code>club-view</code> and <code>club-hawt-view</code> describe static classes in the classical or prototypal sense.  <code>club-hawt-view</code> is a specialization of <code>club-view</code>. Underneath this <code>club-view</code> object (as we&#8217;ll call it for simplicity&#8217;s sake), we have other objects: <code>club-list</code> and <code>club-item</code>.  <code>club-item</code> has three different specializations, as well: <code>club-rock-item</code>, <code>club-disco-item</code>, and <code>club-pop-item</code>.</p>
<p>Note that we must specify both the base (ancestor) and specialization (descendant) classes on the element.  This is because CSS does not specify a way to declare the inheritance relationship in the stylesheet.  This is not a limitation of CSS, in my opinion, just an implementation detail.  </p>
<p>Interestingly, Nicole calls for declarative inheritance in her slides.  This would allow the designer to specify the link to the ancestor class in the stylesheet, rather than in the HTML.  Thus, only <code>club-hawt-view</code> would need to be specified on the object since the stylesheet would declare the link to the ancestor, <code>club-view</code>.  </p>
<p>(Some other <a href="http://lesscss.org/">projects</a> have implemented compile-time solutions to provide declarative inheritance.  However, declarative inheritance in the stylesheet may do little except save some bulk in the HTML, imho.  I&#8217;m on the fence about it.  It feels like it&#8217;s an idea invented out of basic misunderstanding of CSS inheritance, but I can&#8217;t really see any significant down-sides at the moment, either.  In fact, if used correctly, it may help clarify the difference between specialization CSS classes and stateful CSS classes in the HTML.)</p>
<h2 id="oocss-state">OOCSS state</h2>
<p>Now, imagine that we want to place our <code>club-view</code> object into disco mode when the user clicks the button.  In disco mode, we want to highlight certain objects and de-emphasize &#8212; or even hide &#8212; others.  For instance, we don&#8217;t want to show any <code>club-rock-item</code> objects. (Cuz rockers don&#8217;t do disco.)  We could set them to display:none, in this case.  </p>
<p>In a noobish implementation of this behavior, we would simply catch the button&#8217;s click event, query the <code>club-rock-item</code> elements, and hide them.  This is seductively easy (and dangerous) in jQuery:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.dance-mode-selector'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.club-rock-item'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">css</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'display'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'none'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>or dojo:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">dojo.<span style="color: #660066;">query</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.dance-mode-selector'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">onclick</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    dojo.<span style="color: #660066;">query</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.club-rock-item'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">style</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'display'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'none'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The less noobish of us know it&#8217;s a lot more cpu-efficient and flexible if we did this using CSS classes instead of manipulating the nodes&#8217; styles directly.  Let&#8217;s add the following CSS rule and change the click event handler to use it:</p>

<div class="wp_syntax"><div class="code"><pre class="css" style="font-family:monospace;"><span style="color: #6666ff;">.club-disco-mode</span> <span style="color: #6666ff;">.club-rock-item</span> <span style="color: #00AA00;">&#123;</span> <span style="color: #000000; font-weight: bold;">display</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">none</span><span style="color: #00AA00;">;</span> <span style="color: #00AA00;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">dojo.<span style="color: #660066;">query</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.dance-mode-selector'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">onclick</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    dojo.<span style="color: #660066;">query</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.club-view'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">addClass</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'club-disco-mode'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The resulting HTML would look like this:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;section class=&quot;club-view club-hawt-view club-disco-mode&quot;&gt;
    &lt;ul class=&quot;club-list&quot;&gt;
        &lt;li class=&quot;club-item club-rock-item&quot;&gt;1st Item&lt;/li&gt;
        &lt;li class=&quot;club-item club-disco-item&quot;&gt;2nd Item&lt;/li&gt;
        &lt;li class=&quot;club-item club-pop-item&quot;&gt;3rd Item&lt;/li&gt;
    &lt;/ul&gt;
    &lt;button class=&quot;dance-mode-selector&quot;&gt;Let's do Disco!&lt;/button&gt;
&lt;/section&gt;</pre></div></div>

<p>Notice I put the <code>club-disco-mode</code> class on the root object, not the <code>club-rock-item</code> objects (more about this in the next section).  Changing the CSS class instead of direct DOM styling puts the task of deciding how to handle <code>club-disco-mode</code> in the hands of the CSS designer where it belongs.  For instance, once she&#8217;s seen the button jolt upwards (as it would when the <code>club-rock-item</code> object disappeared), she&#8217;d likely throw up a little in her mouth or have a mild seizure induced by this severe UX <em>faux pas</em>!  Then she might mute the colors instead of removing the element from the layout.  </p>
<p>The beauty of this is that there&#8217;s no need to mess with the JavaScript to make this change.  The task of deciding styling and layout for this state change is defined entirely in the CSS.  In fact, the only dependency between the CSS and the JavaScript is the coordination of a single class name, <code>club-disco-mode</code>, on the root element of our object.  You can think of this class name as a message from the JavaScript to the CSS, telling the OOCSS object that it is in a new state.  We&#8217;ve essentially just decoupled the JavaScript from the CSS using a classic method used in object-oriented programming: <em>message passing</em>.  </p>
<p>Not impressed so far?  This is just good CSS practices cast in the light of classical OO, you say?  Ha ha, don&#8217;t worry.  We&#8217;ve only scratched the surface.  In a subsequent blog post, I&#8217;ll show you how cujo.js abstracts the concept of state changes, allowing both CSS (style and layout) and JavaScript (behavioral) state changes to execute in parallel with a single line of code.  </p>
<p>But first, let&#8217;s dig a little deeper into run-time state inheritance&#8230;</p>
<h2 id="oocss-run-time-state">OOCSS run-time state inheritance</h2>
<p>In our &#8220;club&#8221; app, we can also treat the repeated <code>club-item</code> elements as objects, too.  When we change the state of the root <code>club-view</code> object to <code>club-disco-mode</code>, we&#8217;ve also changed the state of all of the <code>club-item</code> objects.  We can take advantage of this by declaring OOCSS rules like the one below.  This rule is just like the earlier rule, but the style declarations have been changed to something less seizure-inducing to somebody with UX sensitivities:</p>

<div class="wp_syntax"><div class="code"><pre class="css" style="font-family:monospace;"><span style="color: #6666ff;">.club-disco-mode</span> <span style="color: #6666ff;">.club-rock-item</span> <span style="color: #00AA00;">&#123;</span> <span style="color: #000000; font-weight: bold;">background-color</span><span style="color: #00AA00;">:</span> <span style="color: #cc00cc;">#ccc</span><span style="color: #00AA00;">;</span> <span style="color: #000000; font-weight: bold;">color</span><span style="color: #00AA00;">:</span> <span style="color: #cc00cc;">#777</span><span style="color: #00AA00;">;</span> <span style="color: #00AA00;">&#125;</span> <span style="color: #808080; font-style: italic;">/* grayed-out */</span></pre></div></div>

<p>You could read this as <em><code>club-rock-item</code> objects under the state of <code>club-disco-mode</code></em>.  If we wanted to be even more explicit, we could write it like this:</p>

<div class="wp_syntax"><div class="code"><pre class="css" style="font-family:monospace;"><span style="color: #6666ff;">.club-view</span><span style="color: #6666ff;">.club-disco-mode</span> <span style="color: #6666ff;">.club-rock-item</span> <span style="color: #00AA00;">&#123;</span> <span style="color: #000000; font-weight: bold;">background-color</span><span style="color: #00AA00;">:</span> <span style="color: #cc00cc;">#ccc</span><span style="color: #00AA00;">;</span> <span style="color: #000000; font-weight: bold;">color</span><span style="color: #00AA00;">:</span> <span style="color: #cc00cc;">#777</span><span style="color: #00AA00;">;</span> <span style="color: #00AA00;">&#125;</span> <span style="color: #808080; font-style: italic;">/* grayed-out */</span></pre></div></div>

<p>This translates to <em><code>club-rock-item</code> objects under <code>club-view</code> objects in the <code>club-disco-mode</code> state</em>.  Here we see how the <code>club-rock-item</code> objects inherit the state of their ancestor(s) and how we can define the style attributes of those objects in response to that state.  In the more explicit variant, we&#8217;ve also increased the specificity, which may not be desirable in all situations, so the shorter variant is also acceptable as long as it can&#8217;t be interpreted ambiguously.  </p>
<p>So, why did I declare the rules this way?  Why didn&#8217;t I change the state on the <code>club-rock-item</code> objects instead of the <code>club-view</code> object?  Because the button&#8217;s stated purpose is to change the state of the entire object, not of only the <code>club-item</code> objects!  Too often, we JavaScript engineers concentrate too much on the task at hand (manipulating the <code>club-rock-item</code> elements), not the semantic meaning of the user&#8217;s action (to change the state of the <code>club-view</code> object).  </p>
<p>Let&#8217;s revisit the <code>club-hawt-view</code> specialization class to better illustrate an example of why this is so important.  When this class is applied to our object, we potentially inherit a whole new set of CSS rules.  One of these rules could define an entirely different layout or a different styling.  Maybe in a <code>club-hawt-view</code> we&#8217;ve turned up the heat a bit:</p>

<div class="wp_syntax"><div class="code"><pre class="css" style="font-family:monospace;"><span style="color: #6666ff;">.club-hawt-view</span> <span style="color: #00AA00;">&#123;</span> <span style="color: #000000; font-weight: bold;">background-color</span><span style="color: #00AA00;">:</span> <span style="color: #cc00cc;">#fa7</span><span style="color: #00AA00;">;</span> <span style="color: #000000; font-weight: bold;">color</span><span style="color: #00AA00;">:</span> <span style="color: #cc00cc;">#500</span><span style="color: #00AA00;">;</span> <span style="color: #00AA00;">&#125;</span> <span style="color: #808080; font-style: italic;">/* red on orange! HAWT! */</span></pre></div></div>

<p>It just wouldn&#8217;t fit to de-emphasized the <code>club-rock-item</code> objects with a gray background, anymore.  The gray and orange clash.  Instead, when we&#8217;re in the <code>club-disco-mode</code> state, let&#8217;s embolden the font on the emphasized objects and just change the font color on the de-emphasized <code>club-rock-item</code>, not the background.  Let&#8217;s also add a dotted border around the whole object (yah, yah, I know this is getting really damn ugly, but hey, I&#8217;m an engineer):</p>

<div class="wp_syntax"><div class="code"><pre class="css" style="font-family:monospace;"><span style="color: #6666ff;">.club-hawt-view</span><span style="color: #6666ff;">.club-disco-mode</span> .club-disco-item<span style="color: #00AA00;">,</span>
<span style="color: #6666ff;">.club-hawt-view</span><span style="color: #6666ff;">.club-disco-mode</span> <span style="color: #6666ff;">.club-pop-item</span> <span style="color: #00AA00;">&#123;</span> 
    <span style="color: #000000; font-weight: bold;">font-weight</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">bold</span><span style="color: #00AA00;">;</span> 
<span style="color: #00AA00;">&#125;</span> 
<span style="color: #6666ff;">.club-hawt-view</span><span style="color: #6666ff;">.club-disco-mode</span> <span style="color: #6666ff;">.club-rock-item</span> <span style="color: #00AA00;">&#123;</span> <span style="color: #000000; font-weight: bold;">background-color</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">transparent</span><span style="color: #00AA00;">;</span> <span style="color: #000000; font-weight: bold;">color</span><span style="color: #00AA00;">:</span> <span style="color: #cc00cc;">#777</span><span style="color: #00AA00;">;</span> <span style="color: #00AA00;">&#125;</span> 
<span style="color: #6666ff;">.club-hawt-view</span><span style="color: #6666ff;">.club-disco-mode</span> <span style="color: #00AA00;">&#123;</span> <span style="color: #000000; font-weight: bold;">border</span><span style="color: #00AA00;">:</span> <span style="color: #933;">1px</span> <span style="color: #993333;">dotted</span> pink<span style="color: #00AA00;">;</span> <span style="color: #00AA00;">&#125;</span></pre></div></div>

<p>The key point is that we didn&#8217;t have to change the JavaScript to deal with the specialized, <code>club-hawt-view</code> object.  We still just passed the same <code>club-disco-mode</code> message to the OOCSS <code>club-view</code> object from the JavaScript in response to a button click:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">dojo.<span style="color: #660066;">query</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.dance-mode-selector'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">onclick</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    dojo.<span style="color: #660066;">query</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.club-view'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">addClass</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'club-disco-mode'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// still the same exact code!</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<h2 id="oocss-decreases-risk">OOCSS decreases risk</h2>
<p>This has been a simple example, but you can start to imagine why using JavaScript to programmatically change styling starts to get ugly.  Here&#8217;s what the code might look like if we used JavaScript instead of CSS:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">dojo.<span style="color: #660066;">query</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.dance-mode-selector'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">onclick</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    dojo.<span style="color: #660066;">query</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.club-item'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">forEach</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>dojo.<span style="color: #660066;">hasClass</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'club-disco-item'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> dojo.<span style="color: #660066;">hasClass</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'club-pop-item'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            dojo.<span style="color: #660066;">style</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'fontWeight'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'bold'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
            dojo.<span style="color: #660066;">style</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span> backgroundColor<span style="color: #339933;">:</span> <span style="color: #3366CC;">'transparent'</span><span style="color: #339933;">,</span> color<span style="color: #339933;">:</span> <span style="color: #3366CC;">'#777'</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    dojo.<span style="color: #660066;">style</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'border'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'1px dotted pink'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This is not reusable code, nor is it very maintainable once you start getting into more complex, real-life projects.  Brian pointed out to me that the general complexity of the situation can be summarized as O(n^m), where n == the total number of CSS classes on a node and m is the number of ancestry levels we may need to manipulate.  If we&#8217;re handling just 3 CSS classes on 3 levels, we&#8217;ve got up to 27 separate cases to consider in code.  </p>
<p>Worst of all, we&#8217;ve inextricably tied our button and our <code>club-item</code> elements together.  If we were to suddenly need a variation of the <code>club-view</code> objects without the <code>club-item</code> objects at all, we&#8217;d be forced to branch yet again.  </p>
<p>As Brian said in his post, declarative code &#8212; such as CSS &#8212; is inherently less risky to modify than procedural code.  </p>
<h2 id="oocss-for-ie">OOCSS in ancient browsers</h2>
<p>The astute CSS developer will have identified several problems with all of the CSS I&#8217;ve shown.  Specifically, none of it will work in IE6 at all!  Combination class selectors (<code>.club-hawt-view.club-disco-mode</code>, for instance) and transparency weren&#8217;t supported in IE until version 7.  Not to worry, cujo.js fixes those automatically.  It also fixes several other CSS2.1 and CSS3 shortcomings in IE.  cujo.js doesn&#8217;t come close to bringing IE up to CSS3 specifications, though, so don&#8217;t get too excited.  cujo.js only fixes IE enough to allow OOCSS to work to its fullest potential while also removing the dependencies between CSS, HTML, and JavaScript.  Separation of concerns has always been a major goal of CSS, but only CSS3 finally fulfills it.  More on that in yet another future blog post.</p>
<p><strong>[update]<br />
For years I thought IE6 didn&#8217;t support combination class selectors!  People are telling me that they work as long as you order the classes correctly (<code>.bar.foo {}</code> versus <code>.foo.bar {}</code>).  I must always order them the way that doesn&#8217;t work.  I&#8217;ll do some further testing and verify.<br />
[/update]</strong></p>
<p>You likely also noticed that Brian is using CSS3 transitions in his project.  Transitions are a critically powerful tool in any UX designers toolkit.  Unfortunately, IE and Firefox  still don&#8217;t support transitions (as of September 2010).  No biggie, cujo.js fixes that, too.  We&#8217;ve even extended transitions to include more popular timing functions such as bounce, elastic, sine, etc.  We&#8217;re also investigating other, more advanced types of transitions to emulate common use cases that don&#8217;t fit the CSS3 transitions model at all.  </p>
<p>For instance, transitions alone can&#8217;t animate an element being tossed into the trash.  Too often the element being deleted and the trash icon don&#8217;t share the same offsetParent or there&#8217;s an ancestor with overflow:hidden somewhere between.  For situations like this, you&#8217;d typically have to append the node to some common ancestor (likely the body element) and then animate it from the original location to the trash icon.  That kind of sequence comes in handy for accessibility-friendly alternatives to drag-and-drop &#8212; as well as a few other use cases.  So, we&#8217;ll be investigating ways to allow the CSS designer to take control of complex transitions like these without tinkering with the engineer&#8217;s JavaScript.</p>
<p>Still not convinced of the benefits of OOCSS?  Next we&#8217;ll see how to apply it in a client-side MVC architecture.  OOCSS becomes even more powerful when you combine it with view-controllers based on OOJS and ultra-simple, inheritable templates I&#8217;ve dubbed OOHTML.</p>
<p>What do you think so far?  Does OOCSS make sense?  Have you already used it in an MVC-based environment?  Let me know!</p>
]]></content:encoded>
			<wfw:commentRss>http://unscriptable.com/2010/08/31/cujo-js-oojs-oocss-and-oohtml-part-1/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
	</channel>
</rss>
