<?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/"
	xmlns:series="http://unfoldingneurons.com/"
	>

<channel>
	<title>AaronHardy.com &#187; module</title>
	<atom:link href="http://aaronhardy.com/tag/module/feed/" rel="self" type="application/rss+xml" />
	<link>http://aaronhardy.com</link>
	<description>For all your Aaron Hardy needs.</description>
	<lastBuildDate>Fri, 20 Apr 2012 14:53:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>JavaScript Architecture: RequireJS Dependency Management</title>
		<link>http://aaronhardy.com/javascript/javascript-architecture-requirejs-dependency-management/</link>
		<comments>http://aaronhardy.com/javascript/javascript-architecture-requirejs-dependency-management/#comments</comments>
		<pubDate>Wed, 21 Mar 2012 02:35:23 +0000</pubDate>
		<dc:creator>Aaron Hardy</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[amd]]></category>
		<category><![CDATA[backbone.js]]></category>
		<category><![CDATA[dependency management]]></category>
		<category><![CDATA[module]]></category>
		<category><![CDATA[requirejs]]></category>
		<category><![CDATA[template]]></category>
		<category><![CDATA[underscore.js]]></category>

		<guid isPermaLink="false">http://aaronhardy.com/?p=1324</guid>
		<description><![CDATA[In JavaScript Architecture: Organization and Quality, we discussed the importance of breaking apps down into very small, decoupled pieces following the single responsibility principle. Small pieces are generally easier to comprehend than a mess of large peices. Some devs coming from other languages feel like they can only build a few large, spaghetti JavaScript files [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="/javascript/javascript-architecture-organization-and-quality/">JavaScript Architecture: Organization and Quality</a>, we discussed the importance of breaking apps down into very small, decoupled pieces following the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" target="_blank">single responsibility principle</a>. Small pieces are generally easier to comprehend than a mess of large peices.</p>
<p>Some devs coming from other languages feel like they can only build a few large, spaghetti JavaScript files for their app. I tend to think this may be caused by three reasons:</p>
<ul>
<li>That&#8217;s the way JavaScript has been done in the past.</li>
<li>Loading many JavaScript files requires many HTTP requests resulting in longer load times.</li>
<li>Dependency management is hard in JavaScript.</li>
</ul>
<p>Don&#8217;t stoop to these excuses. We can do better than that and today there are fantastic libraries and standards that can help us out.  However, let&#8217;s see what the above problems mean.<span id="more-1324"></span></p>
<p><strong>That&#8217;s the way JavaScript has been done in the past. </strong>Unfortunately, that&#8217;s true.  For years many teams developed within one or two large JavaScript files containing thousands of lines of code.  It goes without saying that maintainability was very poor.  It&#8217;s difficult to wrap our minds and <a href="http://en.wikipedia.org/wiki/Integrated_development_environment" target="_blank">IDEs</a> around thousand of lines of interoperating code and also a nightmare with version control in a team environment.  I do believe this is a large contributor to why JavaScript has had a bad wrap in the dev community for so long.</p>
<p><strong>Loading many JavaScript files requires many HTTP requests resulting in longer load times.</strong> It&#8217;s true. Each time a JavaScript file is loaded it requires the overhead of an inidiviual HTTP request and, unfortunately, if you list many script tags in your page the files will load in sequence, not in parallel.</p>
<p><strong>Dependency management is hard in JavaScript.  </strong>By splitting code out into many files, you must keep track of which files depend on each other and make sure they&#8217;re loaded in the right order.  This can be a messy long list and easy to mess up later down the line.  For example:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>script src<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;script3.js&quot;</span><span style="color: #339933;">&gt;&lt;/</span>script<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>script src<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;script1.js&quot;</span><span style="color: #339933;">&gt;&lt;/</span>script<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>script src<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;script13.js&quot;</span><span style="color: #339933;">&gt;&lt;/</span>script<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>script src<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;script7.js&quot;</span><span style="color: #339933;">&gt;&lt;/</span>script<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>script src<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;script6.js&quot;</span><span style="color: #339933;">&gt;&lt;/</span>script<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>script src<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;script12.js&quot;</span><span style="color: #339933;">&gt;&lt;/</span>script<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>script src<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;script4.js&quot;</span><span style="color: #339933;">&gt;&lt;/</span>script<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>script src<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;script11.js&quot;</span><span style="color: #339933;">&gt;&lt;/</span>script<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>script src<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;script5.js&quot;</span><span style="color: #339933;">&gt;&lt;/</span>script<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>script src<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;script9.js&quot;</span><span style="color: #339933;">&gt;&lt;/</span>script<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>script src<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;script8.js&quot;</span><span style="color: #339933;">&gt;&lt;/</span>script<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>script src<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;script10.js&quot;</span><span style="color: #339933;">&gt;&lt;/</span>script<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>script src<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;script2.js&quot;</span><span style="color: #339933;">&gt;&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></div></div>

<p>This is troubling enough on a single-man project but even more-so within a team.</p>
<h2>Modules</h2>
<p>Let&#8217;s get nostalgic for a moment. A few years back, using JavaScript on the server-side was just starting to get hot. Server-side libraries and JavaScript engines were being deployed but they didn&#8217;t have a good, standard API for working with one another and defining dependencies. Getting one library to work with another required some finagling and it was obvious that if JavaScript were to scale it would need some common APIs.</p>
<p>In January 2009, Kevin Dangoor wrote a blog post titled <a href="http://www.blueskyonmars.com/2009/01/29/what-server-side-javascript-needs/" target="_blank">What Server Side JavaScript Needs</a> outlining just that&#8211;what server-side JavaScript needed. The list included:</p>
<ul>
<li>Cross-interpreter standard library</li>
<li>Standard interfaces</li>
<li>Standard way to include other modules</li>
<li>Package up code for deployment and distribution</li>
<li>Install packages and their dependencies</li>
<li>Package repository</li>
</ul>
<p>As a means to fulfill these needs, he created a Google group named <a href="http://groups.google.com/group/commonjs" target="_blank">ServerJS</a> where like-minded folk could collaborate. Soon enough, the group realized that many of these goals weren&#8217;t necessarily limited to the server-side and renamed the group to <a href="http://www.commonjs.org/" target="_blank">CommonJS</a>.</p>
<p>One of the standards that CommonJS worked toward was that of a <a href="http://wiki.commonjs.org/wiki/Modules" target="_blank">module</a>.  A module is a contained piece of code (How&#8217;s that for vague?) that defines not only that it is a module itself but which other modules it depends on to correctly function.  When calling for module B, module B might call for module G and module M, which might call for modules D and W.  By having a module standard, dependency management becomes easier. Rather than keeping some sort of implicit master list that must be kept in order, each module just defines its own dependencies and that mapping can be used to determine required resources and the order in which they must be loaded.</p>
<h2>AMD</h2>
<p>The module concept was great for server-side development as it addressed how to synchronously load modules based on dependency definitions, but the JavaScript devs on the browser-side got a bit jealous.  Why should such awesomeness be confined to the server?  Sure, module loading needs to be done asynchronously in the browser, but that didn&#8217;t mean the concept of modules and dependency definitions couldn&#8217;t be applied.</p>
<p>The <a href="https://github.com/amdjs/amdjs-api/wiki/AMD" target="_blank">Asynchronous Module Definition</a>, or AMD, was born for this purpose. It takes the module and dependency definition API from the server-side and applies it to the asynchronous paradigm of the browser. </p>
<h2>RequireJS</h2>
<p>So what does <a href="http://requirejs.org/" target="_blank">RequireJS</a> have to do with this? Well, even though we can define our modules and their dependencies with AMD, we need something smart that can take this dependency map, load the modules, and execute the modules in order.  That&#8217;s the role RequireJS plays.  Both RequireJS and AMD are open source, popular, and well-curated by <a href="https://twitter.com/#!/jrburke" target="_blank">James Burke</a>.</p>
<h2>Defining and Requesting Modules</h2>
<p>At this point let&#8217;s jump straight into some code and hopefully the concepts will start to solidify.  Almost always, a module is defined within a single file and, vice-versa, a single file only contains a single module definition.  Defining a module, at its core, is as simple as the code below.  Let&#8217;s assume it&#8217;s within a file called book.js.</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;">&#123;</span>
    title<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;My Sister's Keeper&quot;</span><span style="color: #339933;">,</span>
    publisher<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Atria&quot;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>We now have a book module. <code>define()</code> is a RequireJS function.  When we call it, we&#8217;re essentially saying, &#8220;Register what I&#8217;m passing you as a module.&#8221;  By default, RequireJS assumes the module name is the file path following the base url (don&#8217;t get your panties in a twist&#8211;we&#8217;ll get to that in a minute) excluding the extension.  In this case, that means that &#8220;book&#8221; is our assumed module name.  When other code asks RequireJS for the &#8220;book&#8221; module, RequireJS will return the object we just defined above.  Now let&#8217;s make a &#8220;bookshelf&#8221; module in a new file named bookshelf.js and see how we can request the book module into it.</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;">'book'</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>book<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>
		listBook<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;">alert</span><span style="color: #009900;">&#40;</span>book.<span style="color: #660066;">title</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>Notice this one&#8217;s a bit different than the book module.  The book module didn&#8217;t have any dependencies so it was a bit simpler.  Here, we&#8217;re defining an array of dependencies for our bookshelf&#8211;in this case, book.  The second parameter is a callback function.  If book.js hasn&#8217;t been loaded into the app yet, RequireJS will go fetch it from the server.  Once book.js is loaded and the book module is registered, RequireJS will execute our callback function and pass the module (the book object we defined previously) in as a parameter. The argument name isn&#8217;t technically significant.  We could have just as easily said <code>function(a1337Book)</code> or used whatever name we wanted.  In this case, it makes sense to have our argument name match the module name.  Whatever object we return from this callback function will be registered with RequireJS as the bookshelf module.  In our case, it&#8217;s an object with an <code>listBook()</code> method that alerts the book&#8217;s title.</p>
<p>RequireJS tries to be as efficient as possible when loading multiple modules. For example, if multiple dependencies are listed, RequireJS will load all the dependencies as fast as possible in parallel.</p>
<h2>App Setup</h2>
<p>So&#8230;how do we get this party started? Let&#8217;s first start by getting our html page set up. Here&#8217;s how it looks:</p>

<div class="wp_syntax"><div class="code"><pre class="html4strict" style="font-family:monospace;"><span style="color: #00bbdd;">&lt;!DOCTYPE html&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">html</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">head</span>&gt;</span>
		<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">title</span>&gt;</span>RequireJS Example<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">title</span>&gt;</span>
		<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">script</span> data-main<span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;js/main&quot;</span> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;js/libs/require.js&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">script</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">head</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">body</span><span style="color: #66cc66;">/</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">html</span>&gt;</span></pre></div></div>

<p>Quite literally, you can build a large application without adding anything else to your html file just by manipulating the body&#8217;s content using JavaScript and loading html snippets/templates using Require.  We&#8217;ll get there.  For now, take notice that there&#8217;s a <code>data-main</code> attribute.  This tells RequireJS where our bootstrap file is&#8211;in our case, it&#8217;s main.js that lives under a js directory (it assumes main has a js extension).</p>
<p>main.js is what we could call our bootstrap file. We&#8217;ll make ours look like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">require<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span>
	<span style="color: #3366CC;">'bookshelf'</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>bookshelf<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	bookshelf.<span style="color: #660066;">listBook</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>Because we specified this file as our <code>data-main</code> in our html file, RequireJS will load it as soon as possible and it will be immediately executed.  You&#8217;ll notice this has a lot of similarities to our previous modules but instead of calling <code>define()</code> it calls <code>require()</code>.  The <code>define()</code> function&#8211;at least when dependencies are defined&#8211;really does three things: (1) loads the dependencies specified, (2) calls the callback function once dependencies are loaded, and (3) registers the return value from the callback function as the module.  The <code>require()</code> function only does #1 and #2, not #3&#8211;hence the function names &#8220;define&#8221; vs. &#8220;require&#8221;.  In the case of main.js, it&#8217;s just a bootstrap file.  I don&#8217;t need to have a &#8220;main&#8221; module registered with RequireJS because nothing will be calling for it as a dependency.</p>
<p>Our bootstrap lists our &#8220;bookshelf&#8221; module as a dependency.  Assuming the bookshelf module hasn&#8217;t already been registered with RequireJS, it will load bookshelf.js.  Once it loads bookshelf.js, it will see that bookshelf has the book module listed as a dependency. If the book module hasn&#8217;t already been registered, it will then load book.js. Once that&#8217;s done and book and then bookshelf have registered their respective objects as modules with RequireJS, the callback in main.js will be executed and bookshelf will be passed through.  At that point we can do whatever we want with bookshelf.  If needed, we can list multiple module dependencies and they will all be passed into the callback as soon as they&#8217;re all loaded and registered with RequireJS.</p>
<h2>Configuration</h2>
<p>Previously I mentioned the concept of a base url.  By default, the base url is whatever directory contains the bootstrap file.  In my case, I put main.js under a js directory along with book.js and bookshelf.js.  This means, in my case, my base url is /js/.  Now let&#8217;s say instead of placing all my js files directly under the js directory, I moved book.js and bookshelf.js to /js/model/.  Now my main.js would need to look like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">require<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span>
	<span style="color: #3366CC;">'model/bookshelf'</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>bookshelf<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	bookshelf.<span style="color: #660066;">listBook</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>Now main knows the correct location of bookshelf.js.  Likewise, bookshelf.js would list the book dependency as <code>model/book</code> even though book and bookshelf live in the same directory.</p>
<p>This brings us to RequireJS configuration.  At the top of my bootstrap file, I usually perform my configuration. main.js might look like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">require.<span style="color: #660066;">config</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
	baseUrl<span style="color: #339933;">:</span> <span style="color: #3366CC;">'/another/path'</span><span style="color: #339933;">,</span>
	paths<span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #3366CC;">'myModule'</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">'a/b/c/d/myModule'</span>
		<span style="color: #3366CC;">'templates'</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">'../templates'</span><span style="color: #339933;">,</span>
		<span style="color: #3366CC;">'text'</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">'libs/text'</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>
&nbsp;
require<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span>
	<span style="color: #3366CC;">'bookshelf'</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>bookshelf<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	bookshelf.<span style="color: #660066;">listBook</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>In this case, I&#8217;ve manually changed my base url to something completely different.  Personally, I&#8217;ve never needed to configure this but it&#8217;s there to demonstrate one of the <a href="http://requirejs.org/docs/api.html#config" target="_blank">many configuration options available</a>.  I also demonstrated how to configure paths.  Paths are really just shortcuts.  In this case, rather than having to type out &#8220;a/b/c/d/myModule&#8221; when listing dependencies, I can just type &#8220;myModule&#8221;.  I&#8217;ve set up a path (shortcut) for accessing a templates directory that is a sibling to my js directory.  I&#8217;ve also set up a path (shortcut) for accessing the RequireJS <a href="http://requirejs.org/docs/api.html#text" target="_blank">text! plugin</a> more easily.</p>
<h2>Class Modules</h2>
<p>So far, our modules have all been object instances; bookshelf was an object and book was an object.  In reality, modules are very often classes. When using Backbone, modules are classes much more often than not.  The bookshelf <i>class</i> needs the book <i>class</i>, for instance.  It can then instantiate a bunch of books or whatever it needs to do using the book class.  If an instance of the class needs to be passed to different <a href="/javascript/javascript-architecture-backbone-js-views/">Backbone views</a>, for example, it would be passed through the recipient view&#8217;s constructor or other method.  You&#8217;ll start to see that listing dependencies is similar to listing imports in languages like Java or ActionScript.  It&#8217;s essentially giving you access to another class that you can then use within the class you&#8217;re defining.  You just so happen have the ability to also define and retrieve object instances as modules if you really want to. Hopefully this will become more obvious in the next example.</p>
<h2>RequireJS + Backbone</h2>
<p>Using the knowledge from the previous articles in this series and our new-found knowledge of modules, let&#8217;s see an integrated example.  In essence, we have a collection of book models.  We&#8217;re calling the collection a bookshelf.  We have a bookshelf view that loops through the books in the bookshelf, creating a book view for each book in the bookshelf.  The book view displays information about the book.  The views, frankly, are over-architected for the simple stuff we&#8217;re doing here, but I think this demonstrates the integration of RequireJS and Backbone nicely.  If it&#8217;s still unclear, please post a comment and I&#8217;ll do my best to answer.</p>
<p>index.html:</p>

<div class="wp_syntax"><div class="code"><pre class="html4strict" style="font-family:monospace;"><span style="color: #00bbdd;">&lt;!DOCTYPE html&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">html</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">head</span>&gt;</span>
		<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">title</span>&gt;</span>RequireJS Example<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">title</span>&gt;</span>
		<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">script</span> data-main<span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;js/main&quot;</span> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;js/libs/require.js&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">script</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">head</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">body</span><span style="color: #66cc66;">/</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">html</span>&gt;</span></pre></div></div>

<p>js/main.js:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">require.<span style="color: #660066;">config</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #3366CC;">'paths'</span><span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #3366CC;">'jquery'</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">'libs/jquery'</span><span style="color: #339933;">,</span>
		<span style="color: #3366CC;">'backbone'</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">'libs/backbone'</span><span style="color: #339933;">,</span>
		<span style="color: #3366CC;">'underscore'</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">'libs/underscore'</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
require<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span>
	<span style="color: #3366CC;">'view/bookshelf-view'</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>BookshelfView<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	$<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ready</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: #003366; font-weight: bold;">new</span> BookshelfView<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
			el<span style="color: #339933;">:</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'body'</span><span style="color: #009900;">&#41;</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;">&#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>js/view/bookshelf-view.js:</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;">'backbone'</span><span style="color: #339933;">,</span>
	<span style="color: #3366CC;">'underscore'</span><span style="color: #339933;">,</span>
	<span style="color: #3366CC;">'model/bookshelf'</span><span style="color: #339933;">,</span>
	<span style="color: #3366CC;">'view/book-view'</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>Backbone<span style="color: #339933;">,</span> _<span style="color: #339933;">,</span> Bookshelf<span style="color: #339933;">,</span> BookView<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000066; font-weight: bold;">return</span> Backbone.<span style="color: #660066;">View</span>.<span style="color: #660066;">extend</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
		initialize<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;">this</span>.<span style="color: #660066;">collection</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Bookshelf<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span>
				<span style="color: #009900;">&#123;</span>
					title<span style="color: #339933;">:</span> <span style="color: #3366CC;">'A Tale of Two Cities'</span><span style="color: #339933;">,</span>
					author<span style="color: #339933;">:</span> <span style="color: #3366CC;">'Charles Dickens'</span>
				<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
				<span style="color: #009900;">&#123;</span>
					title<span style="color: #339933;">:</span> <span style="color: #3366CC;">'The Good Earth'</span><span style="color: #339933;">,</span>
					author<span style="color: #339933;">:</span> <span style="color: #3366CC;">'Pearl S. Buck'</span>
				<span style="color: #009900;">&#125;</span>
			<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">render</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: #339933;">,</span>
&nbsp;
		render<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;">this</span>.<span style="color: #660066;">collection</span>.<span style="color: #660066;">each</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>book<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
				<span style="color: #003366; font-weight: bold;">var</span> bookView <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> BookView<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
					model<span style="color: #339933;">:</span> book
				<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
				<span style="color: #000066; font-weight: bold;">this</span>.$el.<span style="color: #660066;">append</span><span style="color: #009900;">&#40;</span>bookView.$el<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: #000066; font-weight: bold;">this</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>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>js/view/book-view.js:</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;">'backbone'</span><span style="color: #339933;">,</span>
	<span style="color: #3366CC;">'underscore'</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>Backbone<span style="color: #339933;">,</span> _<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000066; font-weight: bold;">return</span> Backbone.<span style="color: #660066;">View</span>.<span style="color: #660066;">extend</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
		initialize<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;">this</span>.<span style="color: #660066;">render</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: #339933;">,</span>
&nbsp;
		render<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;">this</span>.$el.<span style="color: #660066;">html</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Title: '</span> <span style="color: #339933;">+</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">model</span>.<span style="color: #660066;">get</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'title'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span>
					<span style="color: #3366CC;">'; Author: '</span> <span style="color: #339933;">+</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">model</span>.<span style="color: #660066;">get</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'author'</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: #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></pre></div></div>

<p>js/model/bookshelf.js:</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;">'backbone'</span><span style="color: #339933;">,</span>
	<span style="color: #3366CC;">'model/book'</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>Backbone<span style="color: #339933;">,</span> Book<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000066; font-weight: bold;">return</span> Backbone.<span style="color: #660066;">Collection</span>.<span style="color: #660066;">extend</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
		model<span style="color: #339933;">:</span> Book
	<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>js/model/book.js:</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;">'backbone'</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>Backbone<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000066; font-weight: bold;">return</span> Backbone.<span style="color: #660066;">Model</span>.<span style="color: #660066;">extend</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
		<span style="color: #006600; font-style: italic;">// Intended attributes:</span>
		<span style="color: #006600; font-style: italic;">// title</span>
		<span style="color: #006600; font-style: italic;">// author</span>
		<span style="color: #006600; font-style: italic;">// genre</span>
&nbsp;
		defaults<span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>
			genre<span style="color: #339933;">:</span> <span style="color: #3366CC;">'historical'</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<div class="goodies"><a href="http://code.aaronhardy.com/require-backbone" target="_blank">View Demo</a><br class="break"></div>
<h2>Loading Non-Modules</h2>
<p>Some libraries you want to use in your project don&#8217;t conform to the AMD spec.  In fact, Backbone and Underscore have had their <a href="https://github.com/documentcloud/backbone/pull/710" target="_blank">flirts with conforming to AMD</a> but, at the moment of this writing, aren&#8217;t AMD modules. This means if we add backbone.js to our project and list the Backbone module as a dependency in one of our modules, it won&#8217;t work.  RequireJS will load backbone.js, but nothing in backbone.js registers itself as a module with RequireJS.  RequireJS will throw up its hands and say something like, &#8220;Well, I loaded the file, but there&#8217;s still no Backbone module.&#8221; But, you may have astutely observed that I did exactly that in my previous example and I didn&#8217;t seem to run into problems.  Well, James Burke, the same guy that curates AMD and RequireJS, maintains a <a href="https://github.com/amdjs/backbone" target="_blank">Backbone branch</a> and <a href="https://github.com/amdjs/underscore" target="_blank">Underscore branch</a> that register themselves with RequireJS as modules when they are loaded.  In my example above, I&#8217;m using these Backbone and Underscore branches&#8211;not the official trunk versions.  Technically, you can use the official trunk versions, but some finagling must be done to get them to load in the right order using RequireJS plugins like <a href="http://requirejs.org/docs/api.html#order" target="_blank">order!</a> or <a href="https://github.com/tbranyen/use.js" target="_blank">use!</a> and then you would access the global Backbone and _ variables as would if you weren&#8217;t using RequireJS.  Believe me, <a href="http://stackoverflow.com/questions/8131265/loading-backbone-and-underscore-using-requirejs" target="_blank">you won&#8217;t be the first one to go through your options and figure this one out</a>.</p>
<p>Quite honestly, dealing with non-AMD libraries is by far the most frustrating part about working with RequireJS.  Once you have them set up, though, RequireJS is silky smooth like butter on hot bread.  The good news is that jquery does register itself as an AMD module so you don&#8217;t have to worry about that one.</p>
<p>Alright, so Backbone and Underscore aside, let&#8217;s say we just want to load a single non-AMD JavaScript library file we downloaded off the web. It doesn&#8217;t depend on anything else and we don&#8217;t want to modify its code to make it register itself as an AMD module.  We just want to make sure the file is loaded and then just access the global variable like you normally would if you weren&#8217;t using RequireJS.  Here&#8217;s an example:</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;">'js/libs/coolLib.js'</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><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>window.<span style="color: #660066;">coolLib</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>A few things to notice here: First, our path to the file includes everything from the directory where our html file is located.  This is unlike loading a module that includes everything after our &#8220;base url&#8221; (read above if you don&#8217;t remember what this is).  Second, our path includes the extension.  This is unlike loading a module where the extension is omitted.  Third, because it&#8217;s not a module, RequireJS won&#8217;t pass anything into our callback function.   At that point we just reference coolLib however the coolLib library dictates. RequireJS is just loading the file and, once it&#8217;s loaded, calls our callback function.  Nothing special.</p>
<h2>Loading Templates</h2>
<p>Back in <a href="/javascript/javascript-architecture-underscore-js/">JavaScript Architecture: Underscore.js</a>, we discussed how to break our HTML into templates to prevent it from mingling to closely with our JavaScript.  In the examples we used, we put our HTML templates within script tags.  I then posed the question, &#8220;You might rightfully be wondering how this is scalable if you start to have hundreds of templates in your html file or how you might be able to load them asynchronously only when needed.&#8221;  This is also where RequireJS helps out.</p>
<p>RequireJS has a nice plugin called text!.  You might think I&#8217;m really excited about it because I put an exclamation point next to it. While I do admit it&#8217;s pretty south-beach sexy, really that&#8217;s just the nomenclature of RequireJS plugins because you type something like &#8220;text!myTemplate&#8221; when using them.  The text! plugin allows us to load in files of text&#8211;in our case, HTML templates.  Let&#8217;s see how this works.</p>
<p>First we&#8217;ll <a href="http://requirejs.org/docs/api.html#text" target="_blank">download</a> and place the text! plugin file in js/libs.</p>
<p>We&#8217;ll place book.tpl.html located under a templates directory that&#8217;s a sibling to our js directory:</p>

<div class="wp_syntax"><div class="code"><pre class="html4strict" style="font-family:monospace;"><span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">span</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;label&quot;</span>&gt;</span>Title:<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">span</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">span</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;value&quot;</span>&gt;&lt;%<span style="color: #66cc66;">=</span> <span style="color: #000066;">title</span> %&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">span</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">br</span><span style="color: #66cc66;">/</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">span</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;label&quot;</span>&gt;</span>Author:<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">span</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">span</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;value&quot;</span>&gt;&lt;%<span style="color: #66cc66;">=</span> author %&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">span</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">br</span><span style="color: #66cc66;">/</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">span</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;label&quot;</span>&gt;</span>Genre:<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">span</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">span</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;value&quot;</span>&gt;&lt;%<span style="color: #66cc66;">=</span> genre %&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">span</span>&gt;</span></pre></div></div>

<p>Add some paths to our RequireJS configuration in our main.js to make it easier to use in our modules:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">require.<span style="color: #660066;">config</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #3366CC;">'paths'</span><span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #3366CC;">'jquery'</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">'libs/jquery'</span><span style="color: #339933;">,</span>
		<span style="color: #3366CC;">'backbone'</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">'libs/backbone'</span><span style="color: #339933;">,</span>
		<span style="color: #3366CC;">'underscore'</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">'libs/underscore'</span><span style="color: #339933;">,</span>
		<span style="color: #3366CC;">'templates'</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">'../templates'</span><span style="color: #339933;">,</span>
		<span style="color: #3366CC;">'text'</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">'libs/text'</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Then use the template in book-view.js:</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;">'backbone'</span><span style="color: #339933;">,</span>
	<span style="color: #3366CC;">'underscore'</span><span style="color: #339933;">,</span>
	<span style="color: #3366CC;">'text!templates/book.tpl.html'</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>Backbone<span style="color: #339933;">,</span> _<span style="color: #339933;">,</span> template<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000066; font-weight: bold;">return</span> Backbone.<span style="color: #660066;">View</span>.<span style="color: #660066;">extend</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
		_template<span style="color: #339933;">:</span> _.<span style="color: #660066;">template</span><span style="color: #009900;">&#40;</span>template<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
&nbsp;
		initialize<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;">this</span>.<span style="color: #660066;">render</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: #339933;">,</span>
&nbsp;
		render<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;">this</span>.$el.<span style="color: #660066;">html</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>._template<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">model</span>.<span style="color: #660066;">toJSON</span><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: #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></pre></div></div>

<div class="goodies"><a href="http://code.aaronhardy.com/require-template" target="_blank">View Demo</a><br class="break"></div>
<p>Notice that the template argument is a string variable holding the exact html as found in our template html file.  Then, we use underscore to convert it to a compiled template. We run our book model attributes through the template on <code>render()</code>.  Finally, we update our element&#8217;s inner html with the result.</p>
<p>So what about all those potential HTTP requests?  Here&#8217;s where we optimize&#8230;</p>
<h2>Optimization</h2>
<p>We&#8217;ve broken down all our JavaScript and HTML into granular pieces.  Now we potentially have hundreds of files and unless we do some optimization we would be making hundreds of HTTP requests.  Fortunately, we can leverage the <a href="http://requirejs.org/docs/optimization.html" target="_blank">RequireJS optimizer</a>.</p>
<p>Generally, you set up the optimizer to run on your server before deploying code. The RequireJS optimizer takes your app files, minifies them (shortens your code to make the files really small), and then concatenates them (smashes them together to make a single file).  In the end, you end up with a single file that contains both your JavaScript and your HTML templates. After index.html loads RequireJS, it will load our main.js file.  Our main.js file, this time, will not only contain our expected main.js code but all the minified, concatenated code of the rest of our app&#8211;both JavaScript and HTML templates.  Everything in the file will register itself with RequireJS.  When main starts asking for dependencies and those dependencies start asking for dependencies, RequireJS will recognize that all those modules have already been loaded and forego loading them again.</p>
<p>The optimizer smattering of options.  You can optimize your app down to a few different files representing sections of your app instead of a single large file.  You can also use different minifier libraries, exclude files from concatenation, or even minify CSS.</p>
<h2>Learn More</h2>
<p>We&#8217;ve covered a lot of content but there&#8217;s plenty more to learn about dependency management.  The <a href="http://requirejs.org/" target="_blank">RequireJS website</a> is a great place to start.  If you&#8217;re interested in seeing more examples of Backbone + RequireJS, dig into this <a href="http://addyosmani.github.com/todomvc/dependency-examples/backbone_require/index.html" target="_blank">Todos App example</a>.  And, as always, feel free to provide feedback or ask questions below!</p>
]]></content:encoded>
			<wfw:commentRss>http://aaronhardy.com/javascript/javascript-architecture-requirejs-dependency-management/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<series:name><![CDATA[JavaScript Architecture]]></series:name>
	</item>
		<item>
		<title>Loading a Remote Module into a Local App</title>
		<link>http://aaronhardy.com/flex/loading-a-remote-module-into-a-local-app/</link>
		<comments>http://aaronhardy.com/flex/loading-a-remote-module-into-a-local-app/#comments</comments>
		<pubDate>Sat, 15 Aug 2009 02:39:24 +0000</pubDate>
		<dc:creator>Aaron Hardy</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[crossdomain]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[font]]></category>
		<category><![CDATA[IModuleInfo]]></category>
		<category><![CDATA[loadResourceModule]]></category>
		<category><![CDATA[loadStyleDeclarations]]></category>
		<category><![CDATA[module]]></category>
		<category><![CDATA[ModuleInfo]]></category>
		<category><![CDATA[ModuleManager]]></category>
		<category><![CDATA[ModuleMarshaller]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[style]]></category>
		<category><![CDATA[StyleManager]]></category>
		<category><![CDATA[SWF is not a loadable module]]></category>
		<category><![CDATA[Unable to load resource module]]></category>

		<guid isPermaLink="false">http://aaronhardy.com/?p=295</guid>
		<description><![CDATA[At work, we deal a lot with loading modules residing on remote servers into our applications running locally.  By locally I mean from a local path on our hard drives (the default Flex Builder run/debug settings), not on a local web server instance (localhost).  Depending on what type of module we are loading, we would [...]]]></description>
			<content:encoded><![CDATA[<p>At work, we deal a lot with loading modules residing on remote servers into our applications running locally.  By locally I mean from a local path on our hard drives (the default Flex Builder run/debug settings), not on a local web server instance (localhost).  Depending on what type of module we are loading, we would normally use one of Flex&#8217;s built-in functions to load modules:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// Loading a language resource module:</span>
resourceManager.<span style="color: #006600;">loadResourceModule</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'http://aaronhardy.com/en_US_ResourceModule.swf'</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// Loading a style module (e.g., a compiled font swf):</span>
StyleManager.<span style="color: #006600;">loadStyleDeclarations</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;http://aaronhardy.com/fonts/Astroid.swf&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// Loading miscellaneous modules:</span>
<span style="color: #000000; font-weight: bold;">var</span> moduleInfo:IModuleInfo = ModuleManager.<span style="color: #006600;">getModule</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'http://aaronhardy.com/MyModule.swf'</span><span style="color: #66cc66;">&#41;</span>;
moduleInfo.<span style="color: #0066CC;">load</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>But these methods of importing modules result in errors like the following:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">Unable to <span style="color: #0066CC;">load</span> resource module from http:<span style="color: #808080; font-style: italic;">//aaronhardy.com/en_US_ResourceModule.swf</span>
<span style="color: #0066CC;">Error</span>: Unable to <span style="color: #0066CC;">load</span> style<span style="color: #66cc66;">&#40;</span>SWF is <span style="color: #0066CC;">not</span> a loadable module<span style="color: #66cc66;">&#41;</span>: http:<span style="color: #808080; font-style: italic;">//aaronhardy.com/fonts/Astroid.swf.</span></pre></div></div>

<p><span id="more-295"></span>One way to solve these issues is by <a href="http://bradywhite.net/2008/05/05/flex-3-how-to-load-a-complied-css-swf/" target="_blank">using a crossdomain policy file on the server and then using a local apache instance to run the application</a>.  In my talks with the folks at Adobe, this seems to be their standard workflow which may be why we haven&#8217;t heard more about these problems.  However, my workflow is to NOT have a local web <a href="http://www.hostingobserver.com/server-hosting.php" target="_blank">hosting server</a> running and I don&#8217;t want to have one running just to get around these errors.</p>
<p>As of Flex SDK 3.2, Adobe introduced a new parameter to IModuleInfo.load() for raw module bytes.  As a result, we can now retrieve the remote module&#8217;s raw bytes using a URLLoader and then load them directly as a module using the IModuleInfo.load() method.  The module is now part of the same security domain as the main application and no errors are thrown.</p>
<p>I&#8217;ve bundled up this logic into a class called ModuleMarshaller which is found below.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">package com.<span style="color: #006600;">aaronhardy</span>
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #0066CC;">import</span> flash.<span style="color: #006600;">events</span>.<span style="color: #006600;">ErrorEvent</span>;
	<span style="color: #0066CC;">import</span> flash.<span style="color: #006600;">events</span>.<span style="color: #006600;">Event</span>;
	<span style="color: #0066CC;">import</span> flash.<span style="color: #006600;">events</span>.<span style="color: #006600;">EventDispatcher</span>;
	<span style="color: #0066CC;">import</span> flash.<span style="color: #006600;">events</span>.<span style="color: #006600;">IOErrorEvent</span>;
	<span style="color: #0066CC;">import</span> flash.<span style="color: #006600;">events</span>.<span style="color: #006600;">SecurityErrorEvent</span>;
	<span style="color: #0066CC;">import</span> flash.<span style="color: #006600;">net</span>.<span style="color: #006600;">URLLoader</span>;
	<span style="color: #0066CC;">import</span> flash.<span style="color: #006600;">net</span>.<span style="color: #006600;">URLLoaderDataFormat</span>;
	<span style="color: #0066CC;">import</span> flash.<span style="color: #006600;">net</span>.<span style="color: #006600;">URLRequest</span>;
	<span style="color: #0066CC;">import</span> flash.<span style="color: #006600;">utils</span>.<span style="color: #006600;">ByteArray</span>;
&nbsp;
	<span style="color: #0066CC;">import</span> mx.<span style="color: #006600;">events</span>.<span style="color: #006600;">ModuleEvent</span>;
	<span style="color: #0066CC;">import</span> mx.<span style="color: #006600;">modules</span>.<span style="color: #006600;">IModuleInfo</span>;
	<span style="color: #0066CC;">import</span> mx.<span style="color: #006600;">modules</span>.<span style="color: #006600;">ModuleManager</span>;
&nbsp;
	<span style="color: #808080; font-style: italic;">/**
	 * Dispatched once module loading is complete.
	 */</span>
	<span style="color: #66cc66;">&#91;</span>Event<span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">name</span>=<span style="color: #ff0000;">&quot;ready&quot;</span>, <span style="color: #0066CC;">type</span>=<span style="color: #ff0000;">&quot;mx.events.ModuleEvent&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#93;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">/**
	 * Dispatched if an error is encountered while loading the module.
	 */</span>
	<span style="color: #66cc66;">&#91;</span>Event<span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">name</span>=<span style="color: #ff0000;">&quot;error&quot;</span>, <span style="color: #0066CC;">type</span>=<span style="color: #ff0000;">&quot;mx.events.ModuleEvent&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#93;</span>
&nbsp;
	<span style="color: #808080; font-style: italic;">/**
	 * Loads a remote module.  Specifically, this is a workaround to allow an application being run
	 * locally (not using a web server) to load a module residing on a remote server.
	 * Usually, when attemping to do so using resourceManager.loadResourceModule(),
	 * StyleManager.loadStyleDeclarations(), or IModuleInfo.load() without passing in bytes
	 * results in errors such as the following:
	 *
	 * Error: Unable to load resource module from http://aaronhardy.com/locales/en_US.swf
	 * Error: Unable to load style(SWF is not a loadable module): http://aaronhardy.com/fonts/Astroid.swf.
	 *
	 * Be aware that any module imported with this class may have access to anything within
	 * your application's security sandbox.
	 */</span>
	<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ModuleMarshaller <span style="color: #0066CC;">extends</span> EventDispatcher
	<span style="color: #66cc66;">&#123;</span>
		protected <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #0066CC;">url</span>:<span style="color: #0066CC;">String</span>;
&nbsp;
		<span style="color: #808080; font-style: italic;">/**
		 * Appears to need to be stored in the class scope, otherwise garbage collection
		 * wipes out some of the event handling within IModuleInfo.
		 */</span>
		protected <span style="color: #000000; font-weight: bold;">var</span> module:IModuleInfo;
&nbsp;
		<span style="color: #808080; font-style: italic;">/**
		 * Constructor.
		 * @param url The external module to load into the application.
		 */</span>
		<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> ModuleMarshaller<span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">url</span>:<span style="color: #0066CC;">String</span><span style="color: #66cc66;">&#41;</span>
		<span style="color: #66cc66;">&#123;</span>
			<span style="color: #0066CC;">this</span>.<span style="color: #0066CC;">url</span> = <span style="color: #0066CC;">url</span>;
		<span style="color: #66cc66;">&#125;</span>
&nbsp;
		<span style="color: #808080; font-style: italic;">/**
		 * Starts the loading process by loading in the module as bytes.
		 */</span>
		<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> loadModule<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>:URLLoader
		<span style="color: #66cc66;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">var</span> urlRequest:URLRequest = <span style="color: #000000; font-weight: bold;">new</span> URLRequest<span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">url</span><span style="color: #66cc66;">&#41;</span>;
			<span style="color: #000000; font-weight: bold;">var</span> urlLoader:URLLoader = <span style="color: #000000; font-weight: bold;">new</span> URLLoader<span style="color: #66cc66;">&#40;</span>urlRequest<span style="color: #66cc66;">&#41;</span>;
			urlLoader.<span style="color: #006600;">dataFormat</span> = URLLoaderDataFormat.<span style="color: #006600;">BINARY</span>;
			urlLoader.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>Event.<span style="color: #006600;">COMPLETE</span>, bytesLoadedHandler<span style="color: #66cc66;">&#41;</span>;
			urlLoader.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>IOErrorEvent.<span style="color: #006600;">IO_ERROR</span>, errorHandler<span style="color: #66cc66;">&#41;</span>;
			urlLoader.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>SecurityErrorEvent.<span style="color: #006600;">SECURITY_ERROR</span>, errorHandler<span style="color: #66cc66;">&#41;</span>;
			<span style="color: #b1b100;">return</span> urlLoader;
		<span style="color: #66cc66;">&#125;</span>
&nbsp;
		<span style="color: #808080; font-style: italic;">/**
		 * Once the module bytes are loaded, convert them back into a module within the
		 * application's security domain.
		 */</span>
		protected <span style="color: #000000; font-weight: bold;">function</span> bytesLoadedHandler<span style="color: #66cc66;">&#40;</span>event:Event<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
		<span style="color: #66cc66;">&#123;</span>
			<span style="color: #000000; font-weight: bold;">var</span> styleModuleBytes:ByteArray = ByteArray<span style="color: #66cc66;">&#40;</span>URLLoader<span style="color: #66cc66;">&#40;</span>event.<span style="color: #0066CC;">target</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #0066CC;">data</span><span style="color: #66cc66;">&#41;</span>;
			module = ModuleManager.<span style="color: #006600;">getModule</span><span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">url</span><span style="color: #66cc66;">&#41;</span>;
			module.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>ModuleEvent.<span style="color: #006600;">READY</span>, modReadyHandler<span style="color: #66cc66;">&#41;</span>;
			module.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>ModuleEvent.<span style="color: #0066CC;">ERROR</span>, errorHandler<span style="color: #66cc66;">&#41;</span>;
			module.<span style="color: #0066CC;">load</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">null</span>, <span style="color: #000000; font-weight: bold;">null</span>, styleModuleBytes<span style="color: #66cc66;">&#41;</span>;
		<span style="color: #66cc66;">&#125;</span>
&nbsp;
		<span style="color: #808080; font-style: italic;">/**
		 * Once the module information is loaded, use the factory to create an instance of the
		 * module.
		 */</span>
		protected <span style="color: #000000; font-weight: bold;">function</span> modReadyHandler<span style="color: #66cc66;">&#40;</span>event:ModuleEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
		<span style="color: #66cc66;">&#123;</span>
			ModuleManager.<span style="color: #006600;">getModule</span><span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">url</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">factory</span>.<span style="color: #006600;">create</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
			dispatchEvent<span style="color: #66cc66;">&#40;</span>event.<span style="color: #006600;">clone</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #66cc66;">&#125;</span>
&nbsp;
		<span style="color: #808080; font-style: italic;">/**
		 * Reports errors that may have occurred.
		 */</span>
		protected <span style="color: #000000; font-weight: bold;">function</span> errorHandler<span style="color: #66cc66;">&#40;</span>event:Event<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
		<span style="color: #66cc66;">&#123;</span>
			<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>event is ModuleEvent<span style="color: #66cc66;">&#41;</span>
			<span style="color: #66cc66;">&#123;</span>
				dispatchEvent<span style="color: #66cc66;">&#40;</span>event.<span style="color: #006600;">clone</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
			<span style="color: #66cc66;">&#125;</span>
			<span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>event is ErrorEvent<span style="color: #66cc66;">&#41;</span>
			<span style="color: #66cc66;">&#123;</span>
				dispatchEvent<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> ModuleEvent<span style="color: #66cc66;">&#40;</span>ModuleEvent.<span style="color: #0066CC;">ERROR</span>, <span style="color: #000000; font-weight: bold;">false</span>, <span style="color: #000000; font-weight: bold;">false</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>,
					ErrorEvent<span style="color: #66cc66;">&#40;</span>event<span style="color: #66cc66;">&#41;</span>.<span style="color: #0066CC;">text</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
			<span style="color: #66cc66;">&#125;</span>
		<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>If you&#8217;re loading a style module, you may also want this class, which ensures the style module takes effect in your application immediately after the module is loaded.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">package com.<span style="color: #006600;">aaronhardy</span>
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #0066CC;">import</span> mx.<span style="color: #006600;">events</span>.<span style="color: #006600;">ModuleEvent</span>;
&nbsp;
	<span style="color: #808080; font-style: italic;">/**
	 * Provides the module marshalling functionality of ModuleMarshaller with the ability to
	 * update styles immediately after the module is loaded.
	 */</span>
	<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">class</span> StyleModuleMarshaller <span style="color: #0066CC;">extends</span> ModuleMarshaller
	<span style="color: #66cc66;">&#123;</span>
		<span style="color: #808080; font-style: italic;">/**
		 * If true, forces an immediate update of the application's styles after the module is
		 * loaded.
		 */</span>
		protected <span style="color: #000000; font-weight: bold;">var</span> updateStylesImmediately:<span style="color: #0066CC;">Boolean</span> = <span style="color: #000000; font-weight: bold;">true</span>;
&nbsp;
		<span style="color: #808080; font-style: italic;">/**
		 * Constructor.
		 * @param url The external module to load into the application.
		 * @param update If true, forces an immediate update of the application's styles after
		 *        the module is loaded.
		 */</span>
		<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> StyleModuleMarshaller<span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">url</span>:<span style="color: #0066CC;">String</span>, updateStylesImmediately:<span style="color: #0066CC;">Boolean</span>=<span style="color: #000000; font-weight: bold;">true</span><span style="color: #66cc66;">&#41;</span>
		<span style="color: #66cc66;">&#123;</span>
			<span style="color: #0066CC;">super</span><span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">url</span><span style="color: #66cc66;">&#41;</span>;
			<span style="color: #0066CC;">this</span>.<span style="color: #006600;">updateStylesImmediately</span> = updateStylesImmediately;
		<span style="color: #66cc66;">&#125;</span>
&nbsp;
		<span style="color: #808080; font-style: italic;">/**
		 * @inheritDoc
		 */</span>
		override protected <span style="color: #000000; font-weight: bold;">function</span> modReadyHandler<span style="color: #66cc66;">&#40;</span>event:ModuleEvent<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span>
		<span style="color: #66cc66;">&#123;</span>
			ModuleManager.<span style="color: #006600;">getModule</span><span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">url</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">factory</span>.<span style="color: #006600;">create</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
			<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>updateStylesImmediately<span style="color: #66cc66;">&#41;</span>
			<span style="color: #66cc66;">&#123;</span>
				mx.<span style="color: #006600;">core</span>.<span style="color: #006600;">Singleton</span>.<span style="color: #006600;">getInstance</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;mx.styles::IStyleManager2&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">styleDeclarationsChanged</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
			<span style="color: #66cc66;">&#125;</span>
&nbsp;
			dispatchEvent<span style="color: #66cc66;">&#40;</span>event.<span style="color: #006600;">clone</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<h3>The Dirty Details</h3>
<p>So, why does the ModuleMarshaller function without errors while Flex&#8217;s built-in classes do not?  You might not care, but in case you do, here&#8217;s what I know&#8211;and don&#8217;t know.  First, all the built-in functions end up using ModuleInfo.load() found in ModuleManager.as.  This function uses a Loader to load in the contents of the module.  When the loaded SWF file is accessible and ready for use (i.e., the Loader&#8217;s LoaderInfo object dispatches an Event.INIT event), ModuleInfo.initHandler() is called.  In this function we have the following segment of code:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">factoryInfo = <span style="color: #000000; font-weight: bold;">new</span> FactoryInfo<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #0066CC;">try</span>
<span style="color: #66cc66;">&#123;</span>
    factoryInfo.<span style="color: #006600;">factory</span> = loader.<span style="color: #006600;">content</span> as IFlexModuleFactory;
<span style="color: #66cc66;">&#125;</span>
<span style="color: #0066CC;">catch</span><span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">error</span>:<span style="color: #0066CC;">Error</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#123;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">!</span>factoryInfo.<span style="color: #006600;">factory</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">var</span> moduleEvent:ModuleEvent = <span style="color: #000000; font-weight: bold;">new</span> ModuleEvent<span style="color: #66cc66;">&#40;</span>
        ModuleEvent.<span style="color: #0066CC;">ERROR</span>, event.<span style="color: #006600;">bubbles</span>, event.<span style="color: #006600;">cancelable</span><span style="color: #66cc66;">&#41;</span>;
    moduleEvent.<span style="color: #0066CC;">bytesLoaded</span> = <span style="color: #cc66cc;">0</span>;
    moduleEvent.<span style="color: #0066CC;">bytesTotal</span> = <span style="color: #cc66cc;">0</span>;
    moduleEvent.<span style="color: #006600;">errorText</span> = <span style="color: #ff0000;">&quot;SWF is not a loadable module&quot;</span>;
    dispatchEvent<span style="color: #66cc66;">&#40;</span>moduleEvent<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #b1b100;">return</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Notice how it takes the content from the loader and attempt to cast it as an IFlexModuleFactory object.  In this case, loader.content is NOT an IFlexModuleFactory instance, resulting in factoryInfo.factory being set to null.  Later in the function, it checks to see if factoryInfo.factory is null.  If it is, an error is thrown.  This is the origin of the errors you see in your application.</p>
<p>So why does ModuleMarshaller work?  When ModuleMarshaller makes this call:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">module.<span style="color: #0066CC;">load</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">null</span>, <span style="color: #000000; font-weight: bold;">null</span>, styleModuleBytes<span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>It ultimately ends up in the same ModuleInfo.initHandler() function as we saw above.  In both cases the Flex Builder debugger shows that loader.content is of type GeneratedResourceModule1975496797516746634_mx_core_FlexModuleFactory.  However, when we load the module using the raw bytes loaded with a URLLoader, it IS able to cast the object as an IFlexModuleFactory object, resulting in a non-null factoryInfo.factory object and avoiding any error.</p>
<p>Why such similarity yet one is able to be cast while the other is not?  I don&#8217;t know.  That&#8217;s as far as I can go in my debugging quests with what&#8217;s open source.  I assume it has to do with the <a href="http://www.adobe.com/devnet/flashplayer/articles/flash_player_9_security.pdf" target="_blank">Flash Player security</a> but I haven&#8217;t read anything that would specifically explain why the content cannot be cast as an IFlexModuleFactory object when using built-in Flex module loading methods.  If you can fill in the gap or have questions, please feel free to post a comment.  Bon appetit!</p>
]]></content:encoded>
			<wfw:commentRss>http://aaronhardy.com/flex/loading-a-remote-module-into-a-local-app/feed/</wfw:commentRss>
		<slash:comments>48</slash:comments>
		</item>
		<item>
		<title>Loading a Remote Style SWF</title>
		<link>http://aaronhardy.com/flex/loading-a-remote-style-swf/</link>
		<comments>http://aaronhardy.com/flex/loading-a-remote-style-swf/#comments</comments>
		<pubDate>Wed, 15 Apr 2009 02:32:32 +0000</pubDate>
		<dc:creator>Aaron Hardy</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[font]]></category>
		<category><![CDATA[IModuleInfo]]></category>
		<category><![CDATA[loadStyleDeclarations]]></category>
		<category><![CDATA[module]]></category>
		<category><![CDATA[style]]></category>
		<category><![CDATA[StyleManager]]></category>
		<category><![CDATA[swf]]></category>
		<category><![CDATA[SWF is not a loadable module]]></category>

		<guid isPermaLink="false">http://aaronhardy.com/?p=206</guid>
		<description><![CDATA[This post has been replaced by Loading a Remote Module into a Local App. Enjoy!]]></description>
			<content:encoded><![CDATA[<p>This post has been replaced by <a href="/flex/loading-a-remote-module-into-a-local-app/">Loading a Remote Module into a Local App</a>.  Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://aaronhardy.com/flex/loading-a-remote-style-swf/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

