<?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>todd anderson</title>
	<atom:link href="http://custardbelly.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://custardbelly.com/blog</link>
	<description>it&#039;s a long story</description>
	<lastBuildDate>Fri, 13 Apr 2012 10:13:48 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Micro-Library Facades and Dependency Management using RequireJS</title>
		<link>http://custardbelly.com/blog/2012/03/06/facaded-micro-libraries-and-dependency-management-using-requirejs/</link>
		<comments>http://custardbelly.com/blog/2012/03/06/facaded-micro-libraries-and-dependency-management-using-requirejs/#comments</comments>
		<pubDate>Tue, 06 Mar 2012 10:45:30 +0000</pubDate>
		<dc:creator>todd anderson</dc:creator>
				<category><![CDATA[AMD]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[RequireJS]]></category>
		<category><![CDATA[micro-library]]></category>

		<guid isPermaLink="false">http://custardbelly.com/blog/?p=545</guid>
		<description><![CDATA[I recently have been evaluating some JavaScript micro-libraries mainly to see what the community has put out there, read through some code and see what might be appropriate for any upcoming projects, but also to break a dependency on loading libraries that include code that largely goes unused in an application. 
As of late, I [...]]]></description>
			<content:encoded><![CDATA[<p>I recently have been evaluating some JavaScript micro-libraries mainly to see what the community has put out there, read through some code and see what might be appropriate for any upcoming projects, but also to break a dependency on loading libraries that include code that largely goes unused in an application. </p>
<p>As of late, I have been a pretty strong proponent of <a href="https://github.com/amdjs/amdjs-api" target="_blank">AMD</a> (with a favor toward <a href="http://requirejs.org/" target="_blank">RequireJS</a>) largely with the intent of modularized development but also with an ideal of downloading only what is required by the application. Introducing a dependence (and unnecessary download time) on a library that is only fractionally used seems contradictory in the goal of deploying a compact and stream-lined application. That is not to say that such libraries aren&#8217;t useful or have a place; and more often than not, such libraries have a great history, a number of brilliant engineers behind it and proven track record with production-level applications. There is definitely a give and take, and options do need to be weighed on a per-application basis, yet I feel there can be a great benefit in using a collection of libraries that each serve a single purpose.</p>
<p>So with that determination, I have been investigating some JavaScript micro-libraries that are out there in the wild &#8211; from DOM accessors, to routers, to observers. I haven&#8217;t settled on anything to definitively give the OK on using one library over another; just having a bit of fun discovering what the community has to offer &#8211; and hopefully one day can contribute and give back to.</p>
<h2>The Problem</h2>
<p>While test-driving some micro-libraries it quickly became apparent how inefficient my process was. I would start creating a new project to test out a library and copy over numerous files or <em>worse</em> just fill up a directory with files targeting and named after the library I was including. This grew out of control and weakened a proper evaluation of a library with all the clutter; <em>which one was it? where did i use it? why am i so hungry?</em> </p>
<p>Out of a desire to mitigate this confusion, I settled on an approach to provide a consistent API for development of an application through facades that affords the ability to test-drive different micro-libraries with similar responsibilities. The basic premise is to define a common API that I can develop against contextually, and define and swap out abstracted adaptations of different micro-libraries. As such, I can amass a directory of modules that define this API and declare the library I am currently working within a require statement using <a href="http://requirejs.org/" target="_blank">RequireJS</a>. I believe it is more of a poor-man&#8217;s, less-robust and perhaps not production ready approach that <a href="http://addyosmani.com/blog/" target="_blank">Addy Osmani</a> is working on with <a href="https://github.com/addyosmani/backbone-aura" target="_blank">Aura</a> &#8211; a library I am very excited to checkout.</p>
<p>I have some basic examples of the solution I am using at <a href="http://github.com/bustardcelly/requirejs-microlib-facade" target="_blank">http://github.com/bustardcelly/requirejs-microlib-facade</a>.</p>
<h2>Facades</h2>
<p>As mentioned previously, the largest part of this solution is to provide a common API to develop against. I want to have my scripts that interact with an API to pass tests regardless of the dependency passed in &#8211; with the dependence being the facade module that is adapted to the target micro-library. This area is possibly the crux of the whole argument. Which API do you adapt to? Or rather, which implementation of a micro-library should you favor in exposing an API for multiple micro-libraries? A lot of them have similar methods, but the delegate response signatures can vary. It&#8217;s all at the whim of the developer of the micro-library and their vision of the cleanest solution. I don&#8217;t have an answer to this, by the way <img src='http://darko.liquidweb.com/~custardb/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Just bringing it up. I lean towards providing an API that is similar to the most widely-used solution.</p>
<p>Recently I have been evaluating client-side routing libraries that fit perfectly into this modularized facading concept. Particularly, the first library I wanted to test was <a href="https://github.com/mtrpcic/pathjs" target="_blank">PathJS</a> which provided support for <a href="http://diveintohtml5.info/history.html" target="_blank">HTML5 history</a> as well as fall-back to hash tags (plus niceties like parameterized routes, roots, and others). However, as it provided these capabilities, it also provided two different APIs for them. We could go into a discussion of whether this is good practice and whether it should be abstracted away from the front-end developer, but that isn&#8217;t my biggest concern at the moment &#8211; especially as we can mitigate that concern by abstracting each approach into facades that share a common API. The following are examples of the implementations that adapt to the hash tag implementation and the History implementation respectively:</p>
<p><em>/script/router/PathHashTagFacade.js</em></p>
<pre class="brush: jscript; first-line: 1; title: ;">
define( ['../../lib/path.min.js'], function() {

    return {
        map: function( fragment, delegate ) {
            Path.map( '#'+fragment ).to( function() {
                var paramProperty,
                    paramArray = [];
                for( paramProperty in this.params ) {
                    paramArray[paramArray.length] = this.params[paramProperty];
                }
                delegate.apply( this, paramArray )
            });
        },
        root: function( fragment ) {
            Path.root( '#'+fragment );
        },
        init: function( useHistory ) {
            Path.listen();
        }
    };

});
</pre>
<p><em>/script/router/PathHistoryFacade.js</em></p>
<pre class="brush: jscript; first-line: 1; title: ;">
define( ['../selector/SimpleSelectorFacade', '../../lib/path.min.js'], function( $ ) {

    var links = $('a'),
        i = 0, length = links.length;

    for( i; i &lt; length; i++ ) {
        links[i].onclick = function( event ){
            event.preventDefault();

            var location = this.attributes['href'].value;
            location = location.split( '#' ).join( '' );
            Path.history.pushState( {}, '', location );
            return false;
        };
    }

    return {
        map: function( fragment, delegate ) {
            Path.map( fragment ).to( function() {
                var paramProperty,
                    paramArray = [];
                for( paramProperty in this.params ) {
                    paramArray[paramArray.length] = this.params[paramProperty];
                }
                delegate.apply( this, paramArray )
            });
        },
        root: function( fragment ) {
            Path.history.pushState( {}, '', fragment );
        },
        init: function( useHistory ) {
            Path.history.listen( true );
        }
    };
});
</pre>
<p>Within the definition of each module, a dependency on the <a href="https://github.com/mtrpcic/pathjs" target="_blank">PathJS</a> library is declared and loaded prior to entering the load delegate. <a href="https://github.com/mtrpcic/pathjs" target="_blank">PathJS</a> is not provided as an AMD module, so it is accessed using <em>Path</em> globally in both examples. The two differ, however, in their implementation of the their common API: <em>map</em>, <em>root</em>, and <em>init</em>. Let&#8217;s set aside the irony of the fact that I am now loading two files (<em>path.js</em> and either facade file) with the end goal being to minimize load times &#8211; this will be made clearer in the next example; I just wanted to show the possibility this solution provides in also testing implementation with the same library.</p>
<p>The implementations are very similar in the two examples. The former mostly takes input and prepends values with a hash (#). The latter uses the History API on <em>Path</em>, and intercepts click events on links to properly handle then in the context of <em>Path.history</em>.</p>
<p>Just as a quick example of how I would then employ this:</p>
<pre class="brush: jscript; first-line: 1; title: ;">
require( ['script/router/PathHashTagFacade'], handleRouterDependency );

function handleRouteDependency( router ) {
    require( ['script/RouterDependentClient'], function( client ) {
        client.setRouter( router );
    });
};
</pre>
<p>If HTML5 History API was okay&#8217;d for the project and we wanted to utilize the History API on <a href="https://github.com/mtrpcic/pathjs" target="_blank">PathJS</a>, then we just change the loaded dependency in the first <em>require</em>() statement.</p>
<p>If we look back at the two facade examples for the <em>Path</em> library, both <em>map</em> implementations change the way in which a mapped delegate is handed state with regards to how <em>Path</em> is designed to forward along parameterized values. Usually the parameter key/value pairs are filled on a <em>params</em> Object which is then inspected within the delegate method for the mapped URL. In those examples, I have changed the invocation on the delegate to actually provide the parameterized values as arguments. The reason is because another library I am evaluating does such, and I much prefer it.</p>
<p>Another popular routing library is <a href="https://github.com/flatiron/director" target="_blank">Director</a>. We can now provide a facade for that library that adheres to the same API as the other examples and not have to modify any scripts that interact with the routing dependency (aside from the original <em>require</em>() call):</p>
<p><em>/script/router/DirectorFacade.js</em></p>
<pre class="brush: jscript; first-line: 1; title: ;">
define( ['../../lib/director-1.0.7.min.js'],function() {

    var router, root,
        routes = {},
        adapter = {
            map: function( fragment, delegate ) {
                routes[fragment] = delegate;
            },
            root: function( fragment ) {
                if( router === undefined ) {
                    root = fragment;
                }
                else {
                    router.setRoute( fragment );
                }
            },
            init: function( useHistory ) {
                router = new Router( routes );
                router.init();
                if( root !== undefined ) {
                    router.setRoute( root );
                }
            }
        };

    return adapter;

});
</pre>
<p>Now I can swap out the preferred facade at any time during the development cycle of my project and not have to change any application code that depends on the one chosen.</p>
<p>You can checkout the code and an example at <a href="https://github.com/bustardcelly/requirejs-microlib-facade" target="_blank">https://github.com/bustardcelly/requirejs-microlib-facade</a>.</p>
<h2>Evaluation</h2>
<p>This isn&#8217;t going to be an evaluation of the micro-libraries I am currently testing. Perhaps I will do that in another post, but usually I reserve stating my preference on libraries through <a href="http://twitter.com/_toddanderson_" target="_blank">annoying tweets</a>. Rather, I wanted to provide my running list of Pro&#8217;s and Con&#8217;s with regards to this approach of developing an application against a common API that is defined in AMD modules that provide access similarly to underlying micro-libraries that implement the same contextual task differently. I like starting with Con&#8217;s.</p>
<p><strong>Cons:</strong></p>
<li>Adapting to each libraries implementation.</li>
<ul>
<li>
With the glut of micro-libraries out there, it can be a daunting task to simply say that I can fit each one into a similar interface &#8211; much less provide the same outgoing signature on any delegate responders.
</li>
</ul>
<li>Facading to a single task.</li>
<ul>
<li>There are many libraries that are well-suited for a task, but provide implementations for multiple tasks.</li>
<li>Typically, I think of a facade as providing one API for multiple composited pieces that may or may not interact with each other. I can get over the nomenclature, but what if a the same library provides a well-suited implementation for multiple tasks and is not provided as an AMD? I have not addressed cutting down multiple requests for the same library that may be used across multiple facade modules.</li>
</ul>
<li>JavaScript itself.</li>
<ul>
<li>In JavaScript we can not define an Object as being an implementation of a specific Interface nor, consequently, run any tools to ensure that it adheres to one. I am sure there are libraries and &#8216;tools&#8217; out there that can provide a way that makes it appear that an Object needs to or is adhering to an Interface, I am speaking more out-of-the-box: JavaScript doesn&#8217;t have interfaces. <em>Not arguing whether that is right or wrong</em>.</li>
<li>The main advantage of this approach to facade modules is to develop against a consistent API. As such, it is far too easy &#8211; because of the dynamicism of JavaScript &#8211; to lose that across multiple modules, even just in simple spelling mistakes. This calls for more unit testing, which you should be doing anyway (<strong>yes, I am glaring at myself right now</strong>).</li>
</ul>
<p><strong>Pros:</strong></p>
<li>Developing an application against a dependency whose API will not change based on the required underlying micro-library.</li>
<li>Ability to inject, at runtime, a different dependency if required (say, for instance, after having checked browser capabilities).</li>
<li>The use of high-falootin&#8217; buzzwords when describing your approach to colleagues.</li>
<p>Does one outweigh the other? In as far as development, I am leaning toward the <em>Pro&#8217;s</em>, but I do worry that some the <em>Con&#8217;s</em> may deter me from really evaluating a library that may be best-suited, simply because it is too difficult at the time to fit into the defined API.</p>
<h2>Conclusion</h2>
<p>Will I recommend this approach for production-level application deployment? </p>
<p>That is yet to be determined. I still subscribe to the practice that you should compile in (concatenate and minify) all the sources required by an application. So, having the ability to switch the target facade at runtime or on the server by just modifying a line in some script file doesn&#8217;t seem to be the right approach in delivering a web-based application at the moment for me. I would evaluate a handful of libraries, determine the best suited one for the application and include that one (along with the accompanying facade) in my <a href="https://github.com/jrburke/r.js/" target="_blank">r.js build</a>. But I reserve the right to be proven wrong and/or change my mind <img src='http://darko.liquidweb.com/~custardb/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://custardbelly.com/blog/2012/03/06/facaded-micro-libraries-and-dependency-management-using-requirejs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Current Workflow: Developing, Linting, Testing and Distributing JavaScript</title>
		<link>http://custardbelly.com/blog/2012/02/07/current-workflow-developing-linting-testing-and-distributing-javascript/</link>
		<comments>http://custardbelly.com/blog/2012/02/07/current-workflow-developing-linting-testing-and-distributing-javascript/#comments</comments>
		<pubDate>Tue, 07 Feb 2012 14:53:33 +0000</pubDate>
		<dc:creator>todd anderson</dc:creator>
				<category><![CDATA[AMD]]></category>
		<category><![CDATA[JSHint]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[PhantomJS]]></category>
		<category><![CDATA[QUnit]]></category>
		<category><![CDATA[RequireJS]]></category>
		<category><![CDATA[r.js]]></category>

		<guid isPermaLink="false">http://custardbelly.com/blog/?p=513</guid>
		<description><![CDATA[The title is a bit lofty, no? You&#8217;d expect a treatise to follow, but alas it will most likely be a rambling mess about the various tools and libraries I have a current fascination with and why &#8211; the reason, of which, is due to a recent desire to have a proper build system in [...]]]></description>
			<content:encoded><![CDATA[<p>The title is a bit lofty, no? You&#8217;d expect a treatise to follow, but alas it will most likely be a rambling mess about the various tools and libraries I have a current fascination with and why &#8211; the reason, of which, is due to a recent desire to have a proper build system in place to comfortably develop <strong>JavaScript</strong>. </p>
<p>If you have been following along on this blog, you may be aware of the <a href="https://github.com/bustardcelly/massroute-js" target="_blank">massroute_js project i have up on github</a>. I am testing out various <strong>JavaScript</strong> toolkits, libraries and frameworks and have pushed a few up on the repo. As I was finishing up playing around with the last framework, it dawned on me that I didn&#8217;t have an example with <em>NO</em> framework; NO not being the latest the JS framework. NO being no&#8230; but with more face-palm. Perhaps it is telling of the state of <strong>JavaScript</strong> development these days that I am missing a plain vanilla JS example of my <a href="https://github.com/bustardcelly/massroute-js" target="_blank">MassRoute</a> application, and it is all true. I still don&#8217;t have one committed to the repo. However, the reasoning for that is a lengthy one &#8211; I got obsessed with a proper development environment and custom build system <img src='http://darko.liquidweb.com/~custardb/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  By obsessed, I mean I researched a fair bit of tools and libraries involved in the following areas that I thought fit into my workflow:</p>
<ul>
<li>AMD</li>
<li>Code Quality</li>
<li>Unit Testing</li>
<li>Minification / Concatenation</li>
<li>Build / Deploy</li>
</ul>
<p>I intend to address each of these topics in this article and the tools/libraries I found and those I had chosen for my workflow. It should be noted that I was not considered with development and deployment of the other two piece of the webstack &#8211; <strong>HTML</strong> and <strong>CSS</strong>. It is vital to have a good workflow when working with those technologies as well, and especially if all three are part of your job. There are some great tools and libraries out there for developing and shipping <strong>HTML</strong> and <strong>CSS</strong> and perhaps I will dive into that at a later date.</p>
<p>For now, I have created a common library in the <a href="https://github.com/bustardcelly/massroute-js" target="_blank">massroute_js</a> repo to develop what was turning out to be common pieces of the application I was developing against various <strong>JavaScript</strong> libraries out there. In there are the tools and libraries I will discuss in this post along with a simple build script: <a href="https://github.com/bustardcelly/massroute-js/tree/master/massroute-examples/common" target="_blank">https://github.com/bustardcelly/massroute-js/tree/master/massroute-examples/common</a></p>
<p>I will do my best to explain the history and usage behind each tool and library, but will try to not get too in depth as I may get lost in the actual meaning of this post &#8211; which is to highlight the tools and the workflow in which they can be used together. </p>
<h2>AMD</h2>
<p>The <strong>Asynchronous Module Definition</strong> &#8211; commonly referred to as <strong>AMD</strong> &#8211; is a specification that defines how modules and their dependencies can be defined and loaded asynchronously. The asynchronous part of <strong>AMD</strong> fits nicely in a browser environment so as to not block rendering and script execution while loading modules, but the bigger take away for my development purposes is really the modularization of code and dependency management.</p>
<p>There is a larger history behind <a href="https://github.com/amdjs/amdjs-api/wiki/AMD" target="_blank">AMD</a> and its fruition from <a href="http://wiki.commonjs.org/wiki/CommonJS" target="_blank">CommonJS</a> which I will not go into, not only as I do not have enough personal involvement to speak intelligently about such matters, but that <a href="http://tagneto.blogspot.com/?m=1" target="_blank">James Burke</a> and <a href="http://addyosmani.com/blog/" target="_blank">Addy Osmani</a> already have some extremely insightful articles already out there on the webs:</p>
<p><a href="http://tagneto.blogspot.com/2012/01/simplicity-and-javascript-modules.html?m=1" target="_blank">James Burke: Simplicity and JavaScript modules</a><br />
<a href="http://addyosmani.com/writing-modular-js/" target="_blank">Addy Osmani: Writing Modular JavaScript with AMD, CommonJS and ES Harmony</a></p>
<p>I started dabbling and really getting interested in the idea of modular JavaScript when <a href="http://custardbelly.com/blog/2011/10/04/massroute-js-dojo-example/" target="blank">I began using the Dojo toolkit</a>. That was back at 1.6.1 release and the use of <em>dojo.provide</em>, <em>dojo.require</em> and <em>dojo.declare</em>. Now at 1.7, <a href="dojotoolkit.com" target="_blank">Dojo</a> is fully compliant with <strong>AMD</strong>. Here is an article discussing <strong>Dojo</strong>&#8217;s move to <strong>AMD</strong> compatibility: <a href="http://dojotoolkit.org/features/1.6/async-modules" target="_blank">http://dojotoolkit.org/features/1.6/async-modules</a>. <em>Just as an aside &#8211; you really should check out <a href="http://dojotoolkit.org/" target="_blank">Dojo</a>, particularly if you come from a <strong>Flex</strong> background and have happened upon this post.</em></p>
<p>So, with some familiarity and a strong interest to incorporate modular development, I set out to find a library that would fit nicely in my workflow. There are a handful of <strong>AMD</strong>-compatible libraries, most notably <a href="https://github.com/unscriptable/curl" target="_blank">curl</a> from <a href="http://unscriptable.com" target="_blank">John Hann</a>, <a href="http://bdframework.org/bdLoad/" target="_blank">Backdraft</a>, and <a href="http://requirejs.org/" target="_blank">RequireJS</a> from <a href="http://tagneto.blogspot.com/" target="_blank">James Burke</a>. I settled on the last <strong>RequireJS</strong> as, not only because of its ease of use and the cleanest, most concise documentation, but because of its <a href="http://requirejs.org/docs/history.html" target="_blank">author and his history</a> and <a href="https://twitter.com/#!/jrburke" target="_blank">active role in the community</a>; not to mention that the related optimization tool &#8211; <a href="http://requirejs.org/docs/optimization.html" target="_blank">r.js</a> &#8211; was also a good selling point.</p>
<h3>RequireJS</h3>
<p>The <a href="http://requirejs.org/docs/api.html">RequireJS API</a> defines how to define a module as well as how to load modules with dependencies. Along with other niceties, it also provides the ability to define dependency load order and loading of <strong>text</strong> files (including <strong>CSS</strong>).<br />
Just taking some stripped down and generalized examples from the common lib of my <a href="https://github.com/bustardcelly/massroute-js" target="_blank">massroute_js repo</a>, a module is defined as such:</p>
<p><em>/script/com/custardbelly/js/RequestToken.js</em></p>
<pre class="brush: jscript; first-line: 1; title: ;">
define( function() {

    var RequestToken = (function() {
        this.then = function( handler ) {
            ...
        }
    });
    return RequestToken;

})l
</pre>
<p>&gt; and a module with dependencies are defined as so:</p>
<p><em>/script/com/custardbelly/js/Request.js</em></p>
<pre class="brush: jscript; first-line: 1; title: ;">
define( [&quot;com/custardbelly/js/RequestToken&quot;], function( RequestToken ) {

    var Request = (function( url ) {
        this.send = function( variables ) {
            var token = new RequestToken();
            ...
            return token;
        }
    });
    return Request;

});
</pre>
<p>So with these two examples we see how to define modules with and without dependencies, hopefully demonstrating the benefit of modularization but also the beauty of composition through dependency that <strong>AMD</strong> libraries like <a href="http://requirejs.org/" target="_blank">RequireJS</a> provide. </p>
<p>Another great benefit in using RequireJS is that it gets rid of you having to manage your code in namespaces. In other words, this is no longer necessary:</p>
<pre class="brush: jscript; first-line: 1; title: ;">
(function( window ) {
    var massroute = getNamspace( 'com.custardbelly.massroute' );

    function getNamespace( value ) {
        var parts = value.split( '.' ),
            i = 0,
            length = parts.length,
            package, parent = window;

        for( i; i &lt; length; i++ ) {
            package = parts[i];
            parent[package] = parent[package] || {};
            parent = package;
        }
        return parent;
     };

    var Something = function() {
        ....
    };

    massroute.Something = Something;

})( this );
</pre>
<p>What is happening under the hood, loading and reference-wise, is that <strong>RequireJS</strong> (now <em>require</em> on the <strong>window</strong> Object) holds a list of file references in its own <em>contexts.urlMap</em> property &#8211; the key being the normalized string of the module based on configuration and the value being the actual url for that module file. As dependency requests are made, a lookup is made on <strong>require</strong>&#8217;s <em>contexts.loaded</em> property which maps the normalized module string to a flag of already loaded and available. A script tag is actually written and attached to the <strong>DOM</strong> to begin loading of the script just as most script loaders do. What sets it apart is the use of async and datasets. If we take a look at what is appended for the <em>Request</em> module from a previous example:</p>
<pre class="brush: xml; title: ;">
&lt;script type=&quot;text/javascript&quot; charset=&quot;utf-8&quot; async=&quot;&quot; data-requirecontext=&quot;_&quot; data-requiremodule=&quot;com/custardbelly/js/Request&quot; src=&quot;./../script/com/custardbelly/js/Request.js&quot;&gt;&lt;/script&gt;
</pre>
<p>We can see that the values on the datasets directly correspond to those of the key/value pairs in <em>require.context.urlMap</em> for your application. So as these are loaded, the flag in <em>require.context.loaded</em> is flipped. Pretty elegant, and if you are interested in more about <strong>RequireJS</strong>&#8217;s design and the requirements it adheres to, this is a great article: <a href="http://requirejs.org/docs/requirements.html" target="_blank">http://requirejs.org/docs/requirements.html</a>. Now&#8230; back to looking at code.</p>
<p>When it came time to employ these modules, I would <em>require</em>() where my application is responsible for making a request. Let&#8217;s just take on start-up in a main file as an example:</p>
<p><em>/app/main.js</em></p>
<pre class="brush: jscript; first-line: 1; title: ;">
(function( require ) {
    require.config({
        baseUrl: &quot;.&quot;,
        paths: {
            &quot;com&quot;: &quot;./script/com&quot;
        }
    });

    require( ['com/custardbelly/js/Request'], function( Request ) {

        var request = new Request( 'http://somewhere.fun/go'),
            token = request.send({person:'Todd'});

        token.then( relax );

        function relax() {
            console.log( 'ahhh' );
        }
    });
})( requirejs );
</pre>
<p>It should be noted that anything (ie. objects, functions, native objects) can be returned from a module definition. Typically, though, and which is seen from these examples, i tend to return constructors probably due to my class-based language background; in other words, <em>x</em> requires <em>y</em> as <em>x</em> is going to create at least one new instance of it. But you could very well return an object or a function, and the real power comes in when you consider composition and module dependencies&#8230; and for all you <strong>DI</strong> fans out there like me, the cogs might start spinning up in that noggin. I have yet to do a real test-drive of <strong>IoC</strong> containers for <strong>JavaScript</strong> but there must be or could be something that is a perfect match for <strong>RequireJS</strong>. I am aware of <a href="https://github.com/briancavalier/wire" target="_blank">wire</a>, but as I said, have yet to give it a go &#8211; Santa failed on delivering more hours in the day <img src='http://darko.liquidweb.com/~custardb/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  If you know of any, please leave a comment.</p>
<p>So that is where my <strong>AMD</strong> loader choice stands. I have been using it for some time and have been pretty happy. Keep in mind that all these modules are separated to their own files. Depending on the size of the project, that can tally up to a lot of requests. And if we compound that with a slow network and a limited caching capabilities, we&#8217;re talking about trade-offs in even using <strong>AMD</strong>&#8230; unless we can optimize our development workspace down to a reasonable production environment that will go live. We&#8217;ll address those concerns a little later in the article&#8230;</p>
<h3>AMD reading link dump:</h3>
<p><a href="https://github.com/amdjs/amdjs-api/wiki/AMD" target="_blank">AMD specification on GitHub</a><br />
<a href="https://github.com/umdjs/umd" target="_blank">(UMD) Universal Module Definition</a><br />
<a href="http://unscriptable.com/code/AMD-vs-CommonJS/#0" target="_blank">John Hann: AMD vs CommonJS</a><br />
<a href="http://dailyjs.com/2011/12/22/framework/" target="_blank">DailyJS: The How and Why of AMD</a><br />
<a href="http://addyosmani.com/writing-modular-js/" target="_blank">Addy Osmani: Writing Modular JavaScript with AMD, CommonJS and ES Harmony</a><br />
<a href="http://tagneto.blogspot.com/2012/01/simplicity-and-javascript-modules.html?m=1" target="_blank">James Burke: Simplicity and JavaScript modules</a><br />
<a href="http://tomdale.net/2012/01/amd-is-not-the-answer" target="_blank">Tom Dale: AMD is Not the Answer</a><br />
<a href="http://wiki.ecmascript.org/doku.php?id=harmony:modules_examples" target="_blank">ES Harmony modules proposal</a><br />
<a href="http://requirejs.org/" target="_blank">RequireJS</a></p>
<h2>Code Quality</h2>
<p>What makes <strong>JavaScript</strong> so <em>fun</em> is you can get away with a lot of shi&#8230; pped code that is littered with syntactical errors, misspellings, declared and unused variables and not to mention code that is improperly formatted. Such things can cause your application to fail silently and unsuspectingly to a user &#8211; no flag is explicitly raised that the code is failing unless an end-user cares about opening the debugger tools of a browser and submitting tickets for you. Such things you can&#8217;t mitigate and handle properly with more code because it is the code itself&#8230; well, i guess you could wrap everything in a little try&#8230; catch&#8217;s, but that would be silly.</p>
<p>If you are coming to <strong>JavaScript</strong> from a language that gets compiled, finding such mistakes during development might be a bit of a challenge in as far as the IDE department goes. There are a handful of excellent <strong>IDE</strong>s out there targeting web development (I enjoy <a href="http://www.sublimetext.com/2" target="_blank">Sublime Text 2</a>), but the nature of an interpreted language leaves the ability to analyze and catch possible syntax and runtime errors before deploying code a challenge; unlike <strong>SDK</strong>s and <strong>IDE</strong>s that employ compiler tools that can determine errors in live edit or through a pre-compilation build.</p>
<p>That&#8217;s not to say, <em>by any means</em>, that a program has less bugs in a compiled environment than in an interpreted one. It just means you have to be a little more diligent in analyzing and testing your code &#8211; more on testing later. This type of analysis without actually executing or running the code for a program is commonly referred to as <em>linting</em><a href="http://en.wikipedia.org/wiki/Lint_(software)" target="_blank">. When it comes to JavaScript, you can&#8217;t go far into searching for a linter without finding </a><a href="http://www.jslint.com/" target="_blank">JSLint</a>, nor <a href="http://www.jshint.com/" target="_blank">JSHint</a> and their <a href="http://anton.kovalyov.net/2011/02/20/why-i-forked-jslint-to-jshint/" target="_blank">connection</a>. </p>
<p>I won&#8217;t go over the benefits of one or the other, nor their history as there are plenty of articles out there on such. For the benefit of my own development environment and workflow, I have chosen <a href="http://www.jshint.com/" target="_blank">JSHint</a> for linting code &#8211; mainly because of the ease of set-up especially when it comes to disregarding the formatting of my code. I am much more concerned with syntactical errors and do not consider such things as indentation to be detrimental to the performance of the program, especially as it will later be run through minification. That is in no way stating that proper formatting is un-important, especially, especially, especially when working with a team. I do strive to keep a consistent format to my code, and certain IDEs help in some respect with coding standards and conventions, but at this time <a href="http://www.jslint.com/" target="_blank">JSLint</a> is a little too strict and feels a little more like prodding the code into a certain style &#8211; like a master&#8217;s apprentice. Not necessarily a bad thing and I may change my mind at some point, but for now <strong>JSHint</strong> it is. Plus, there is a sweet <a href="https://github.com/uipoet/sublime-jshint" target="_blank">JSHint package</a> for <a href="http://www.sublimetext.com/2" target="_blank">Sublime Text 2</a> that I can hook into a hotkey to check for errors on the current file I have open. </p>
<h3>Code Quality reading link dump:</h3>
<p><a href="http://www.jslint.com/" target="_blank">JSLint</a><br />
<a href="http://www.jshint.com/" target="_blank">JSHint</a><br />
<a href="http://anton.kovalyov.net/2011/02/20/why-i-forked-jslint-to-jshint/" target="_blank">Anton Kovalyov: Why I Forked JSLint to JSHint</a><br />
<a href="https://github.com/uipoet/sublime-jshint" target="_blank">JSHint Sublime Plugin: uipoet/sublime-jshint</a></p>
<h2>Unit Testing</h2>
<p>This topic is too large to really go into discussing methodologies, extolling the virtues of and defining best practices for in this article. As such, I will simply state that I am guilty of not doing enough testing during the design of applications. For a time, when I was getting more familiar with languages and programming in general, creating unit tests for my code seemed more as a distraction from getting down to brass tacks and delivering a product. I&#8217;ll admit that, and the hugely naive stance that it takes <img src='http://darko.liquidweb.com/~custardb/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  That is in no way to say that now I practice good <a href="http://en.wikipedia.org/wiki/Test-driven_development" target="_blank">Test Driven Development</a> (TDD). Far from it; really far from it. But I am trying to get better. More importantly, my thinking has changed in that I now believe unit testing is actually a proper way of testing the <em>design</em> of my application rather than finding errors in the code. I think that was a big leap for me. And, for whatever it may mean, coming to an interpreted language like <strong>JavaScript</strong>, designing and developing upon unit tests becomes even more important to me. <a href="http://www.amazon.com/Test-Driven-JavaScript-Development-Developers-Library/dp/0321683919" target="_blank">Test-Driven JavaScript Development</a> by <a href="http://cjohansen.no/" target="_blank">Christian Johansen</a> has definitely gone a long way in swaying my development practices for <strong>JavaScript</strong>, and I highly recommend picking up this book. </p>
<p>Like I said, it is too much to get into a discussion of <strong>TDD</strong> and unit testing, I wanted more to highlight the choices I have made for my development and deployment workflow in unit testing my code. I looked at and tried out a couple different unit testing frameworks for <strong>JavaScript</strong> &#8211; with <a href="http://pivotal.github.com/jasmine/" target="_blank">Jasmine</a>, <a href="http://hirojs.com/" target="_blank">Hiro</a> and <a href="http://docs.jquery.com/QUnit" target="_blank">QUnit</a> catching my eye. </p>
<h3>QUnit</h3>
<p>I ended up settling with <strong>QUnit</strong> for the following reasons:</p>
<ol>
<li>Familiarity and ease of use.</li>
<li>Easy integration with RequireJS.</li>
<li>Easy and already available source/docs for integration with headless test runners (<a href="http://code.google.com/p/js-test-driver/wiki/QUnitAdapter" target="_blank">JSTestDriver</a>, <a href="http://code.google.com/p/phantomjs/wiki/TestFrameworkIntegration" target="_blank">PhantomJS</a> &#8211; more on this later).</li>
</ol>
<p>All of those are important. That list is really more representative of the order the contact states of a 3-way bulb where it eventually all came together. It was imperative that I could keep developing without choosing a <strong>Unit Testing</strong> framework that influenced the <strong>AMD</strong> library I chose and (as I will go into in a bit) it was necessary for my deployment needs to run the tests in a headless environment; during development, i want to write my tests (hopefully using &#8220;<a href="http://www.markhneedham.com/blog/2009/04/30/coding-dojo-13-tdd-as-if-you-meant-it/" target="_blank"><em>TDD-like-you-mean-it</em></a>&#8220;) and run them quickly and visually, but I also was looking forward to take that work in unit testing unmodified and provide it to a headless test runner when it came to run a full deployment. So <a href="http://docs.jquery.com/QUnit" target="_blank">QUnit</a> fit in nicely&#8230; for now at least. The familiarity and ease of use is a nice initial draw, but the other two are really the weighing factors and I would not mind giving <a href="http://pivotal.github.com/jasmine/" target="_blank">Jasmine</a> more of a go at a later date if i can ensure those two points.</p>
<p>In any event, using <a href="http://requirejs.org/" target="_blank">RequireJS</a> and <a href="http://docs.jquery.com/QUnit" target="_blank">QUnit</a> together is rather straight-forward, especially after finding this <a href="https://gist.github.com/920405" target="_blank">nice gist from drewwells: https://gist.github.com/920405</a>. The main rule to remember is to set <em>autostart</em> to false on <strong>QUnit</strong>, and only invoke :<em>start()</em> once you have required all tests:</p>
<p><em>/test/index.html</em></p>
<pre class="brush: xml; first-line: 6; title: ;">
&lt;script src=&quot;../lib/require-1.0.4.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;lib/qunit.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
    QUnit.config.autostart = false;

    require.config({
        baseUrl: &quot;.&quot;,
        paths: {
            &quot;com&quot;: &quot;../script/com&quot;
        }
    });

    requirejs(['script/RequestTest.js', 'script/RequestTokenTest.js', 'script/RouteStopTest.js'], function() {
        QUnit.start(); // Tests loaded, run tests
    });
&lt;/script&gt;
</pre>
<p>In basic terms, you have replaced adding <em>&lt;script&gt;</em> tags for each test &#8211; as you normally would when working with <strong>QUnit</strong> &#8211; with loading them as modules through <strong>RequireJS</strong>. The tests utilize <strong>RequireJS</strong> as well, but do not define a module; rather require necessary dependencies through <strong>RequireJS</strong> and define tests that <strong>QUnit</strong> will find:</p>
<p><em>/test/script/RequestTest.js</em></p>
<pre class="brush: jscript; first-line: 1; title: ;">
require( ['com/custardbelly/js/RequestToken', 'com/custardbelly/js/Request'], function( RequestToken, Request ) {

    module( &quot;Request Test&quot; );

    test( 'send returns RequestToken', function() {
        var token,
            xhr = new Request( 'http://webservices.nextbus.com/service/publicXMLFeed?command=routeList&amp;a=mbta' );

        token = xhr.send();
        equals( ( token !== 'undefined' ), true, 'Request.send() returns RequestToken' );
    });
    ...
});
</pre>
<p>The source library dependencies are defined in the first argument for <em>require</em>(), while the second argument is a handler with there reference supplied as arguments. As for the <em>module</em>() call, there&#8217;s nothing there now accept the name that will be associated and printed along with the tests but the <strong>QUnit</strong> <em>modules</em> can also be used to define your <em>setUp</em> and <em>tearDown</em> fixtures. <a href="http://docs.jquery.com/QUnit" target="_blank">Check out the docs for more information</a>.</p>
<h3>PhantomJS</h3>
<p>As I mentioned in the previous part of this section, it is a requirement for my deployment process to be able to run my unit tests in a headless environment. As well, it is preferable to not modify the set-up for unit testing in the development environment to run the tests later in deployment. I originally checked out <a href="http://code.google.com/p/js-test-driver/" target="_blank">JsTestDriver</a> for my headless environment as it is undoubtably the most widely known &#8211; and for good reason. It even has an <a href="http://code.google.com/p/js-test-driver/wiki/QUnitAdapter" target="_blank">adapter for QUnit</a>, and I spent a great deal of time to get it working with my <strong>QUnit</strong> + <strong>RequireJS</strong> setup. To no available, however, as <a href="http://groups.google.com/group/requirejs/browse_thread/thread/5113a89cf5f5dc52" target="_blank">this discussion reveals</a> in which script loading is not really supported by <strong>JsTestDriver</strong>, which is required (no pun) as we saw earlier in this article that <strong>RequireJS</strong> writes <em>async</em> <em>&lt;script&gt;</em> tags to the <strong>DOM</strong>.</p>
<p>That discovery led me to <a href="http://www.phantomjs.org/" target="_blank">PhantomJS</a> which I am pretty happy out. As the site states:</p>
<p>&#8220;PhantomJS is a headless WebKit with JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.<br />
PhantomJS is created by <a href="https://twitter.com/AriyaHidayat">Ariya Hidayat</a>.&#8221;</p>
<p>What that basically means is that it is nothing short of awesome, and by executing the <strong>QUnit</strong> adapter script provided at <a href="http://code.google.com/p/phantomjs/wiki/TestFrameworkIntegration" target="_blank">http://code.google.com/p/phantomjs/wiki/TestFrameworkIntegration</a> I could point to my local main file that I use for running unit tests during development and run <strong>PhantomJS</strong> during deployment to stop and report back any failures encountered. Here is an example of that command:</p>
<pre class="brush: bash; title: ;">
./bin/phantomjs run-qunit.js file://localhost/Users/todd/massroute_js/massroute-examples/common/test/index.html
</pre>
<p>I actually played around with <a href="http://www.phantomjs.org/" target="_blank">PhantomJS</a> farther beyond just trying to integrate with my <a href="http://requirejs.org/" target="_blank">RequireJS</a> and <a href="http://docs.jquery.com/QUnit" target="_blank">QUnit</a> set up for deployment, and the <strong>API</strong> it provides is exceptional and proves its use in a variety of automated tasks: <a href="http://code.google.com/p/phantomjs/wiki/Interface" target="_blank">http://code.google.com/p/phantomjs/wiki/Interface</a>.</p>
<p>* <em>If you are interested in how you can hook up additional logging/output for PhantomJS+QUnit, <a href="https://twitter.com/gavincoop" target="_blank">@gavincoop</a> tweeted this gist to me that incorporates output of JUnit XML, which I hadn&#8217;t incorporated into my workflow: <a href="https://gist.github.com/1588423" target="_blank">https://gist.github.com/1588423</a></em></p>
<h3>Unit Testing link dump:</h3>
<p><a href="http://en.wikipedia.org/wiki/Test-driven_development" target="_blank">Test Driven Development</a><br />
<a href="http://pivotal.github.com/jasmine/" target="_blank">Jasmine</a><br />
<a href="http://hirojs.com/" target="_blank">Hiro</a><br />
<a href="http://docs.jquery.com/QUnit" target="_blank">QUnit</a><br />
<a href="http://code.google.com/p/js-test-driver/" target="_blank">JsTestDriver</a><br />
<a href="http://www.phantomjs.org/" target="_blank">PhantomJS</a><br />
<a href="http://www.amazon.com/Test-Driven-JavaScript-Development-Developers-Library/dp/0321683919" target="_blank">Test-Driven JavaScript Development</a> by Christian Johansen.</p>
<h2>Minification &#038; Concatenation (min-concat)</h2>
<p>As I was researching and introducing unit testing for my development workflow, the choice of unit testing framework began to hinge on its integration in a headless testing environment that could be used in a deployment scheme. When it comes to deployment and production-level sources, it is recommended to minify and concatenate scripts. Concatenation has the benefit of minimizing HTTP requests (with a trade off of size of course), and should be done with respect to dependencies; meaning, I would concatenate Service and Token modules together, but not with interactivity utility scripts &#8211; the user may not require one or the other during their session, so there is no need to bundle them together and bloat file size and request response time.</p>
<p>Typically I would save the min-concat for deployment. I would develop and test (both with browser developer tools and unit test) with fully spaced-up, line-break-containing, long-variable-name-using scripts and only min-concat when it came time to push to staging and production. Some say that this may present false positives as I would not be testing with what is to be live code. I would tend to agree and I am looking for a reliable way to fit this into the dev/deploy workflow, but for now it is much easier to test code with the full source using the browser developer tools (though i have heard that there may be new advancements in file swapping a&#8217;la <a href="http://www.charlesproxy.com/" target="_blank">Charles</a> or <a href="http://kevinlangdon.com/serviceCapture/" target="_blank">Service Capture</a> for dev tools).</p>
<p>When it comes to minification and concatenation of <strong>JavaScript</strong> files, there are a handful. When researching the right one to fit into my current development and deployment workflow, I also discovered and kick the tires on some fuller build systems that incorporated min-concat to see if they were something I could use. I highlight a few in the links section of this part as I think they may be beneficial to others, but I stuck with rolling my one build/deployment script mainly due to the dependency (happily and no pun intended <img src='http://darko.liquidweb.com/~custardb/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ) of <a href="requirejs.org" target="_blank">RequireJS</a> in my development.</p>
<h3>Minification</h3>
<p>Here is a quick rundown of the most popular minifier/optimization scripts out there that I see:</p>
<ul>
<li><a href="http://developer.yahoo.com/yui/compressor/" target="_blank">YUI Compressor</a></li>
<li><a href="http://code.google.com/closure/compiler/" target="_blank">Google Closure Compiler</a></li>
<li><a href="https://github.com/mishoo/UglifyJS/">UglifyJS</a></li>
</ul>
<p>In one way or another, most open-source build systems I have come across use one or a coupling of these. Each have their own strengths and compiler options, but I can not speak at length on the benefits outweighing one or the other. The reason that I didn&#8217;t delve into which incorporated better into my workflow was due to my want of modular development and <strong>RequireJS</strong>. So for obvious reasons that lead me to the supported optimizer tool from <strong>RequireJS</strong> &#8211; <a href="http://requirejs.org/docs/optimization.html" target="_blank">r.js</a>.</p>
<p><a href="https://github.com/jrburke/r.js" target="_blank">r.js</a> is an optimizer for JavaScript source files that use the AMD API. It can be configured to use either <strong>UglifyJS</strong>(default) or the <strong>Closure Compiler</strong> and can be run under <a href="http://nodejs.org/" target="_blank">node.js</a> and <a href="http://www.mozilla.org/rhino/" target="_blank">Rhino</a>. It is a minifier and concatenator rolled into one and does so with respect to AMD loaders.</p>
<p>When using <strong>r.js</strong>, you provide a build file that defines your desired configuration in optimization. There is a good base example up in github: <a href="https://github.com/jrburke/r.js/blob/master/build/example.build.js" target="_blank">https://github.com/jrburke/r.js/blob/master/build/example.build.js</a>, and just as a quick example of what I have for a build file for the custom script in <a href="https://github.com/bustardcelly/massroute-js/tree/master/massroute-examples/common" target="_blank">massroute-js/common</a>:</p>
<pre class="brush: jscript; first-line: 1; title: ;">
({
    baseUrl: '../../script',
    name: 'com/custardbelly/js/Request',
    include: ['com/custardbelly/js/RequestToken'],
    out: '../../dist/script/custardbelly.min.js',
    optimize: &quot;closure&quot;,
    wrap: true
})
</pre>
<p>That is the defining the base URL for modules to be used by the AMD loader (<em>baseUrl</em>), the main module (<em>name</em>) and its dependencies (<em>include[]</em>), the output filename (<em>out</em>), preferred optimizer (<em>optimize</em>), and whether or not to wrap the optimized file in <em>(function() { &#8230; }());</em> to encapsulate the code.</p>
<p>Now, for my &#8220;commons&#8221; library that is being developed for the <a href="https://github.com/bustardcelly/massroute-js" target="_blank">massroute-js examples</a>, I have source split up into two packages &#8211; one that may be considered common to my domain, and one that is considered common to the application. Unfortunately, a single build file for <a href="https://github.com/jrburke/r.js" target="_blank">r.js</a> doesn&#8217;t seem to be compatible to define multiple output modules with their own separate dependencies. In remembering the configuration file from previous example, I had thought this would be achievable by placing the <em>name</em>, <em>include</em> and <em>out</em> properties into each element of the modules list available from the <strong>r.js</strong> build API, eg.:</p>
<pre class="brush: jscript; first-line: 1; title: ;">
({
    baseUrl: '../../script',
    dir: '../../dist/script',
    modules: [
        {
            name: 'com/custardbelly/js/Request',
            include: ['com/custardbelly/js/RequestToken'],
            out: 'custardbelly.min.js'
        },
        {
            name: 'com/custardbelly/massroute/model/InflatableModel',
            include: ['com/custardbelly/massroute/model/Route', 'com/custardbelly/massroute/model/RouteStop'],
            out: 'massroute.min.js'
        }
    ],
    optimize: &quot;closure&quot;,
    wrap: true
})
</pre>
<p>In this build file example, I attempted to output two optimized modules &#8211; one each for the <em>custardbelly</em> and <em>massroute</em> namespace, as I figured with the previous example representing a single module output with its configuration, defining them in the list in <em>modules</em> would perform multiple module outputs; which is not the case. That is when i stumbled upon <a href="https://github.com/jrburke/r.js/issues/30#issuecomment-3693033" target="_blank">this ticket in requirejs&#8217; github</a> and gave the solution of using multiple &#8220;single file&#8221; builds, which is what I wound up using in my deployment.</p>
<p>It should be noted that <a href="http://tagneto.blogspot.com" target="_blank">James Burke</a> has also released <a href="https://github.com/jrburke/almond" target="_blank">almond.js</a>, which is a light-weight AMD loader. With this, it is possible to run <strong>r.js</strong> and compile in <strong>almond.js</strong> to remove the dependency of loading the <strong>require.js</strong> library at runtime. I attempted to fold this solution into my deployment build, but ended up not using it mainly because of how <strong>Rhino</strong> looks up resources based on the <em>name</em> property in the <strong>r.js</strong> configuration file; the only way to reliably fold <strong>almond.js</strong> into my optimized library was to include in the same directory as my custom scripts. I generally like to separate my scripts out into folders that rightly define their role and particularly do not intermix third-party libraries with my own scripts. But whatever. I am being a stickler and if it comes a benefit, I will probably incorporate a script that will temporarily copy the <em>/external/lib/almond.js</em> file into my <em>/scripts</em> directory only to remove if after running optimization with <a href="http://requirejs.org/docs/optimization.html" target="_blank">r.js</a>.</p>
<h3>Min/Concat link dump:</h3>
<p><a href="http://developer.yahoo.com/performance/rules.html" target="_blank">Yahoo!: Best Practices For Speeding Up Your Website</a><br />
<a href="http://developer.yahoo.com/yui/compressor/" target="_blank">YUI Compressor</a><br />
<a href="http://code.google.com/closure/compiler/" target="_blank">Google Closure Compiler</a><br />
<a href="https://github.com/mishoo/UglifyJS/">UglifyJS</a><br />
<a href="http://requirejs.org/docs/optimization.html" target="_blank">r.js</a><br />
<a href="https://github.com/jrburke/almond" target="_blank">almond.js</a></p>
<h3>Other min-concat build systems</h3>
<p><a href="https://github.com/cjohansen/juicer" target="_blank">juicer: A command line tool for JavaScript and CSS developers.</a><em>(Incredible work and will probably use again at a later date)</em><br />
<a href="https://github.com/fat/smoosh" target="_blank">smoosh: something like a himalountain.</a> <em>(I personally liked using this)</em><br />
<a href="https://github.com/cowboy/grunt" target="_blank">grunt: A command line build tool for JavaScript projects.</a><br />
<a href="https://github.com/webpro/jaguarundi" target="_blank">jaguarandi: Ant build script to optimize and version Javascript, CSS, and HTML files</a><br />
<a href="https://github.com/tobie/modulr-node/" target="_blank">modulr-node: Resolves and concatenates CommonJS module dependencies for use in the browser.</a></p>
<h2>Deployment</h2>
<p>The last couple sections of research &#8211; headless test runners and min-concat optimization &#8211; were leading up to deployment. These two areas are outside of my development workflow and are part of my deployment workflow. Truth be told, I will probably incorporate running headless test on the optimized scripts as well to make sure that the compiler didn&#8217;t ming anything once in production, but for now I am putting trust in the fact that it does not &#8211; and any runtime errors that occur are due to my source code (it happens!). </p>
<p>In any event, here we stand with being tasked to fold in linting, testing, optimization and deployment. In the last section, I highlighted a few build systems I had come across as I was researching minification and concatenation of <strong>JavaScript</strong>, but I wanted to roll my own deployment script just so I can tailor it to my needs. I am not intending to provide it as an open source project as I feel it is very specific, but it is available and being continually developed from the <a href="https://github.com/bustardcelly/massroute-js/tree/master/massroute-examples/common" target="_blank">massroute-js github</a> if you are interested.</p>
<p>When it came to creating the build script(s), I sat for moment to think about the environment I wanted to use. I took under consideration what I thought should be considered of a client-side developer to have installed on her machine. Is it too much to ask to install <a href="http://nodejs.org/" target="_blank">node.js</a> or <a href="http://www.ruby-lang.org/en/" target="_blank">ruby</a> for the sole purpose of running a development/deployment script? Should I stick with old reliable <a href="http://ant.apache.org/" target="_blank">ANT</a> as it is pretty much accepted as a requirement for current and past projects? I answered &#8220;No&#8221; to both, though I do think the first question is a good discussion for another time; and I have written so many <strong>ANT</strong> build scripts that I wanted to do something different&#8230;</p>
<p>I settled on a simple <a href="http://www.gnu.org/software/make/manual/make.html" target="_blank">Makefile</a>, as it is quick and easy to understand and fulfills its current purpose:</p>
<pre class="brush: bash; first-line: 1; title: ;">
# Lint - JSHint
LINT = ./build/lint/jshint
SRC_DIR = ./script

# Tests - PhantomJS
PHANTOM = ./build/phantom/phantomjs
PHANTOM_QUNIT_RUNNER = ./build/phantom/run-qunit.js
TEST_DIR = ./test
TEST_INDEX_URL = file://localhost/Users/todd/massroute_js/massroute-examples/common/test/index.html

# Min/Concat - r.js
R_JS = java -classpath ./build/rhino/js.jar:./build/closure/compiler.jar org.mozilla.javascript.tools.shell.Main
R_DIR = ./build/require

all: lint phantom optimize

lint:
	@echo '==&gt; JSHint $&lt;'
	@@for file in `find ${SRC_DIR} -name &quot;*.js&quot;`; \
		do echo ===Linting $$file...===; ${LINT} $$file; done;
	@echo

phantom:
	@echo '==&gt; Phantom $&lt;'
	${PHANTOM} ${PHANTOM_QUNIT_RUNNER} ${TEST_INDEX_URL};
	@echo

optimize:
	@echo '==&gt; r.js $&lt;'
	@@for file in `find ${R_DIR} -name &quot;*.build.js&quot;`; \
	   do echo ===r.js: $$file...===; ${R_JS} ${R_DIR}/r.js -o $$file; done;
	@echo
</pre>
<p>Certainly, this sort of <a href="http://www.gnu.org/software/make/manual/make.html" target="_blank">Makefile</a> is intended for the lead developer or automated system to run at deployment, rather than being shared across multiple developers during development as the constants are pretty system specific. If this development/deployment workflow were to introduced into a company workflow, I would probably opt for <a href="http://ant.apache.org/" target="_blank">ANT</a> or <a href="http://rake.rubyforge.org/" target="_blank">Rake</a> &#8211; which I intend to add to the repository at some point. As well, this deployment is simply just for JavaScript. I may find down the line that a more complete system is required which can optimize HTML, CSS, images, etc. and actually deploy files to a server. The playing field then widens and sticking with <strong>Make</strong> is probably not going to be the optimal solution, and I may rethink requiring <a href="http://nodejs.org/" target="_blank">node.js</a> or <a href="http://www.ruby-lang.org/en/" target="_blank">ruby</a> environments for deployment.</p>
<h2>Conclusion</h2>
<p>So there we have it. My current development and deployment workflow. Subject to change, as always. Decisions towards testing and optimization were definitely weighted with respect to my choice in <a href="https://github.com/amdjs/amdjs-api/wiki/AMD" target="_blank">AMD</a>, but I feel <a href="http://requirejs.org/" target="_blank">RequireJS</a> presents a strong enough case for modular development, so I am pretty confortable and happy with it at the moment. It was a great learning experience researching and testing all the various frameworks, libraries and systems in finding what worked and I appreciate the openness of the <strong>JavaScript</strong> community in releasing such quality and well-documented code; I hope to return the favor some day.</p>
<p>A quick round-up from the original listing of what i wanted to achieve, marked with the decision:</p>
<ul>
<li>AMD &#8211; <a href="http://requirejs.org/">RequireJS</a></li>
<li>Code Quality &#8211; <a href="http://www.jshint.com/">JSHint</a></li>
<li>Unit Testing &#8211; <a href="http://docs.jquery.com/QUnit">QUnit</a> &#038; <a href="http://www.phantomjs.org/">PhantomJS</a></li>
<li>Minification / Concatenation &#8211; <a href="https://github.com/jrburke/r.js/" target="_blank">r.js</a> (+<a href="http://code.google.com/closure/compiler/">Closure Compiler</a>)</li>
<li>Build / Deploy &#8211; <a href="http://www.gnu.org/software/make/manual/make.html">make</a></li>
</ul>
<p>cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://custardbelly.com/blog/2012/02/07/current-workflow-developing-linting-testing-and-distributing-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>massroute-js: knockout example</title>
		<link>http://custardbelly.com/blog/2011/11/14/massroute-js-knockout-example/</link>
		<comments>http://custardbelly.com/blog/2011/11/14/massroute-js-knockout-example/#comments</comments>
		<pubDate>Mon, 14 Nov 2011 14:07:15 +0000</pubDate>
		<dc:creator>todd anderson</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[knockoutjs]]></category>

		<guid isPermaLink="false">http://custardbelly.com/blog/?p=496</guid>
		<description><![CDATA[I have created a github repository at http://github.com/bustardcelly/massroute-js to explore various JavaScript libraries and frameworks with a focus of delivering a web-based application for real-time transportation data made available from MassDOT. This article intends to address my findings in an exploration of one of those libraries or frameworks that have caught my interest. If you [...]]]></description>
			<content:encoded><![CDATA[<p><em>I have created a github repository at <a href="http://github.com/bustardcelly/massroute-js" target="_blank">http://github.com/bustardcelly/massroute-js</a> to explore various JavaScript libraries and frameworks with a focus of delivering a web-based application for <a href="http://www.eot.state.ma.us/developers/realtime/" target="_blank">real-time transportation data made available from MassDOT</a>. This article intends to address my findings in an exploration of one of those libraries or frameworks that have caught my interest. If you have any suggestions for another <strong>JavaScript</strong> library/framework please leave a comment.</em></p>
<p><em>It should also be noted that some explanations may be heavily influenced by my experience in developing for the <strong>Flash Platform</strong> and particularly their relation to the <strong>ActionScript</strong> and the <strong>Flex</strong> mark-up language.</em></p>
<p>The massroute-js example using Knockout can be found at: <a href="http://github.com/bustardcelly/massroute-js/tree/master/massroute-examples/" target="_blank">http://github.com/bustardcelly/massroute-js/tree/master/massroute-examples/</a></p>
<p>The initial draw to test out the <a href="http://knockoutjs.com/" target="_blank">Knockout</a> library was its basis on the <a href="http://en.wikipedia.org/wiki/Model_View_ViewModel" target="_blank">Model-View-View Model</a> (MVVM) architectural pattern. I won&#8217;t go into to much detail about what MVVM is and what it can provide, as there are already many good explanations out there; I will just quickly point you to <a href="http://en.wikipedia.org/wiki/Model_View_ViewModel" target="_blank">wikipedia</a> and its <a href="http://knockoutjs.com/documentation/observables.html#mvvm_and_view_models" target="_blank">explanation on the Knockout site directly</a>. If you are not up for clicking those links, MVVM is an architectural design pattern &#8211; like <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" target="_blank">Model-View-Controller</a> (MVC) &#8211; but is similar to the <a href="http://martinfowler.com/eaaDev/uiArchs.html" target="_blank">Model-View-Presenter</a> (MVP) pattern. In basic terms, the ViewModel of MVVM is similar to the Presenter of MVP in so much as the View is responding to changes on an abstraction of the Model rather than directly on the Model. However, they differ in that the ViewModel is an abstraction of not only the properties of the Model but also provides an API that reflects the actions taken by a View that in turn affect the state of the Model; the Presenter from MVP has more of a role in being knowledgable about the View directly &#8211; subscribing to events and accessing the View&#8217;s API. These are both markedly different from the MVC approach in which the Controller is only responsible for updating the Model in response to user actions on the View &#8211; providing an indirect relationship of the View to the Controller in which the state of the View is directly related to the state of the Model.</p>
<h3>Data Binding and Observables</h3>
<p>At the heart of <a href="http://knockoutjs.com/" target="_blank">Knockout</a>&#8217;s MVVM implementation is <em>data binding</em>. If you stumbled upon here and are coming from the Flex world, the concept of data binding is probably all too familiar. In basic terms, data binding is a process in which one party, bound to a change on another party, is automatically updated to reflect that change when it occurs. Most notably, data binding is utilized in updating UI that is bound to a model representing state. </p>
<p>In broader terms, data binding utilizes the <strong>Observer Pattern</strong>. If you are familiar with subscribing to events and assigning handlers that respond to change in UI, then you are already aware of using an <strong>Observer</strong>. Within the implementation of the data binding concept, the subscription and publishing mechanisms are hidden away and as a change to the <em>subject</em> (the one subscribed to) occurs, they change is published to a <em>dependent</em> (the subscriber). What i mean by &#8220;hidden away&#8221; is that you as a developer do not directly establish this relationship by setting up event listeners and implementing the logic in response to a change in state. Libraries that allow for data binding provide a way in which you can establish this relationship which is then wired behind the scenes. Again, if you are coming from the Flex world, this is familiar in the use of curly brackets ({}) in-line in your MXML or (my preference) the methods of the <em>BindingUtils</em> class.</p>
<p>Using Knockout, you define <em>observables</em> which dispatch notifications when changes to a value occur. Properties on a ViewModel are defined with observables to which an element can be bound, creating a dependency that is reflected in the rendering of the UI. Let&#8217;s get away from wordy word-words and see an implementation of a ViewModel and how it relates to declarations of elements on the DOM. At the core you will have your model object that defines &#8211; among other things &#8211; the <strong>observables</strong>:</p>
<pre class="brush: jscript; first-line: 1; title: ;">
var model = {
    title: ko.observable('Hello World'),
    items: ko.observableArray()
};
</pre>
<p>If your dependency is on value change to one object &#8211; whether it be a string, number, boolean, object, etc. &#8211; you use <em>ko.observable</em> as defined in this example for the <em>title</em> property on the <strong>model</strong> object.  If you want to detect and notify of changes to a collection of objects, you use <em>ko.observableArray</em>.  You can also define <strong>dependent observables</strong> which are properties that are updated based on the value of other observables. Just a quick example of dependent observables:</p>
<pre class="brush: jscript; title: ;">
model.greeting = ko.dependentObservable( function() {
    return this.title + ', how are ya?';
}, model );
</pre>
<p>These observables and their notifications are then managed once you register the model:</p>
<pre class="brush: jscript; title: ;">
ko.applyBindings( model );
</pre>
<p>On the HTML side, you use the datasets to define the binding definitions. <a href="http://knockoutjs.com/" target="_blank">Knockout</a> recognizes the <strong>data-bind</strong> attribute on elements of the DOM and &#8211; in broad, general terms &#8211; evaluates the attribute value as a binding expression. As a quick example of how this would look in using the model from the previous examples, the mark-up would look something like the following:</p>
<pre class="brush: xml; first-line: 1; title: ;">
&lt;header&gt;
    &lt;hgroup&gt;
        &lt;h1 data-bind=&quot;text: title&quot;&gt;&lt;/h1&gt;
        &lt;h2 data-bind=&quot;text: greeting&quot;&gt;&lt;/h2&gt;
    &lt;/hgroup&gt;
&lt;/header&gt;
&lt;section&gt;
    &lt;nav&gt;
        &lt;ul data-bind='foreach: items'&gt;
            &lt;li class='list-item'&gt;
            	&lt;a data-bind=&quot;attr: {href:url}, text: label&quot;&gt;&lt;/p&gt;
            &lt;/li&gt;
        &lt;/ul&gt;
    &lt;/nav&gt;
&lt;/section&gt;
</pre>
<p>As changes to the <em>title</em> property on the model occur, both items in the header group will be updated on the DOM (<em>greeting</em> because of its dependency on <em>title</em>), and as the <em>item</em> collection changes so will the un-order list, with the declared list item serving as the item renderer to be used in adding child elements to the list (more on that in the next section).</p>
<p>Properties are updated by <em>invoking</em> the observable. That may seem a little strange at first, as you are probably more familiar with updating object properties using the = expression. But the properties, once declared as <em>ko.observables</em>, are actually not the primitive objects they represent and are functions themselves. So if we were to update the properties on the model in the previous examples, that would be done as in the following:</p>
<pre class="brush: jscript; title: ;">
model.title( 'Hello Again' );
model.items( [
    {label:'foo', url:'http://foo.com'},
    {label:'bar', url:'http://bar.com'}
] );
</pre>
<p>And that is important to remember, as the same goes for accessing the property value. Accessing <strong>model.title</strong> will actually return the observable function, not the string value. To get the underlying value, you use <em>ko.utils.unwrapObservable</em>, as in the following example:</p>
<pre class="brush: jscript; title: ;">
var titleValue = ko.utils.unwrapObservable( model.title() );
</pre>
<p>You can also subscribe to changes explicitly in JavaScript, and if you are coming from the Flex world, this is pretty much like the BindingUtils:</p>
<pre class="brush: jscript; title: ;">
var itemSubscription = model.items.subscribe( function( collection ) {
    // do something really cool that will win you friends and influence others.
});
...
// No longer need to win friends and influence others.
itemSubscription.dispose()
</pre>
<p>That is just a birds-eye-view quick run-down of how the view model plays a part in knockout, and i really encourage you to check out the document on their site to see all of what is capable: <a href="http://knockoutjs.com/documentation/introduction.html" target="_blank">http://knockoutjs.com/documentation/introduction.html</a>.</p>
<h3>Control Flow</h3>
<p>If you&#8217;ve looked at those examples or are familiar with <a href="https://github.com/SteveSanderson/knockout" target="_blank">Knockout</a> and have checked out the <a href="https://github.com/bustardcelly/massroute-js/tree/master/massroute-examples/knockout" target="_blank">massroute-js/knockout example I put on github</a>, you might see that things are set up a bit different. Indeed they are; I had begun my example using knockout-1.2.1.js, but had found this post toward the end of my finishing the example: <a href="http://blog.stevensanderson.com/2011/08/31/knockout-1-3-0-beta-available/" target="_blank">http://blog.stevensanderson.com/2011/08/31/knockout-1-3-0-beta-available/</a>. I was so taken with the changes to <em>Control Flow Bindings</em>, that I moved my example to that. If this is all new to you and that last sentence was complete gibberish, I&#8217;ll explain; I just wanted to give a heads up if any of you were curious enough to check out their current examples and look at <a href="https://github.com/bustardcelly/massroute-js/tree/master/massroute-examples/knockout" target="_blank">my project on github</a>.</p>
<p>What I take away from the concept of <em>Control Flow Binding</em>, is that you can define (and Knockout with manage) the existence of DOM elements based on a ViewModel condition. If you are coming from the Flex world, you can think of it somewhat in terms of the State API and state-based declarations for elements, such as <em>includeIn</em> and <em>excludeFrom</em>. But it goes a little farther in that, in so much as it is also allows for and is used in rendering whole graphs of DOM elements based on a condition and model data. A common example is lists, and the UI elements you define are the item renderers &#8211; depending on the existence of a collection, graphs of defined HTML elements are rendered, added to the DOM and handed data.</p>
<p>Prior to the current work on <a href="http://knockoutjs.com/" target="_blank">Knockout</a> that is in beta and <a href="https://github.com/SteveSanderson/knockout" target="_blank">available from the projects github</a>, there was a dependency on an external templating engine &#8211; for example, <a href="http://api.jquery.com/category/plugins/templates/" target=_blank">jquery-tmpl</a> which was commonly the go-to engine since there is already a dependency on <a href="http://jquery.com/" target="_blank">jQuery</a> -that would allow you to define UI elements to use in deferred rendering within the Control Flow and state of the target ViewModel. In the <a href="https://github.com/SteveSanderson/knockout/tree/master/build/output" target="_blank">latest beta for Knockout</a>, you can now declare those elements inline within the document and the library will handle the existence and rendering based on the defined condition.</p>
<p>To give a quick example, here is the whole section in the <a href="https://github.com/bustardcelly/massroute-js/tree/master/massroute-examples/knockout" target="_blank">massroute-js/knockout</a> project that displays the list of routes available from the real-time MBTA feed:</p>
<pre class="brush: xml; first-line: 1; title: ;">
&lt;section id=&quot;routesection&quot; data-bind=&quot;visible: routes.visible&quot;&gt;
    &lt;h1 data-bind=&quot;text: routes.title&quot;&gt;&lt;/h1&gt;
    &lt;p data-bind=&quot;if: routes.list().length === 0&quot;&gt;loading...&lt;/p&gt;
    &lt;nav data-bind=&quot;if: routes.list().length &gt; 0&quot;&gt;
        &lt;ul data-bind='foreach: routes.list'&gt;
            &lt;li class='route-item list-item icon-list-item' style='cursor: pointer;'&gt;
                &lt;figure&gt;
                    &lt;img src='style/image/bus_icon.png' /&gt;
                    &lt;figcaption data-bind=&quot;text: title&quot;&gt;&lt;/figcaption&gt;
                &lt;/figure&gt;
            &lt;/li&gt;
        &lt;/ul&gt;
    &lt;/nav&gt;
&lt;/section&gt;
</pre>
<p>If this is example you are seeing that utilizes the <a href="http://knockoutjs.com/">Knockout</a> library, i will just quickly mention that Knockout recognizes the <em>data-bind</em> attribute and interprets the value as an expression allowing you to associated DOM elements with a ViewModel declaratively. It is too much of a discussion to go into the dataset attribute and their usage, but wanted to give a brief explanation of how it is relevant to this snippet and will now defer you to this documentation: <a href="http://dev.w3.org/html5/spec/Overview.html#embedding-custom-non-visible-data" target="_blank">http://dev.w3.org/html5/spec/Overview.html#embedding-custom-non-visible-data</a></p>
<p>To get a clearer picture of <em>Control Flow</em> and element templating, take a look at the &lt;ul&gt; and &lt;li&gt; fragments of this example. A <em>foreach</em> is declared on the binding for the <strong>ul</strong> element, which in turn will render a new instance of the list item declared within the ul for this example. In simpler terms, this allows us to define the item renderer for the list declaratively inline within the control flow definition. A pretty cool addition to the library, and one in which, even though i am just test-driving Knockout, warranted me using <a href="https://github.com/SteveSanderson/knockout/tree/master/build/output" target="_blank">Knockout 1.3.0 beta</a> to do away with using another dependency on a template engine.</p>
<p>There are also some other additions to the library which I am excited to try out, most notably Binding Providers and Throttling. Check out this post from <a href="http://blog.stevensanderson.com/" target="_blank">Steven Sanders</a> about <a href="https://github.com/SteveSanderson/knockout/tree/master/build/output" target="_blank">Knockout 1.3.0 Beta</a>: <a href="http://blog.stevensanderson.com/2011/08/31/knockout-1-3-0-beta-available/" target="_blank">http://blog.stevensanderson.com/2011/08/31/knockout-1-3-0-beta-available/</a>.</p>
<h3>Links</h3>
<p>I encourage you to check out the Knockout home page at <a href="http://knockoutjs.com/">http://knockoutjs.com/</a> and the awesome interactive tutorials they have available at <a href="http://learn.knockoutjs.com" target="_blank">http://learn.knockoutjs.com</a>. You can also checkout the latest developments from github &#8211; <a href="https://github.com/SteveSanderson/knockout">https://github.com/SteveSanderson/knockout</a> &#8211; and, again, check out what is coming in the next version from this nice article: <a href="http://blog.stevensanderson.com/2011/08/31/knockout-1-3-0-beta-available/">http://blog.stevensanderson.com/2011/08/31/knockout-1-3-0-beta-available/</a>.</p>
<p>You can checkout the rest of my massroute-js/knockout example on github here: <a href="https://github.com/bustardcelly/massroute-js/tree/master/massroute-examples/knockout">https://github.com/bustardcelly/massroute-js/tree/master/massroute-examples/knockout</a>. Questions, comments and constructive berating are welcome (though not so much the last one).</p>
]]></content:encoded>
			<wfw:commentRss>http://custardbelly.com/blog/2011/11/14/massroute-js-knockout-example/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Deferred content for Flex 4 Group using [DefaultProperty]</title>
		<link>http://custardbelly.com/blog/2011/11/11/deferred-content-for-flex-4-group-using-defaultproperty/</link>
		<comments>http://custardbelly.com/blog/2011/11/11/deferred-content-for-flex-4-group-using-defaultproperty/#comments</comments>
		<pubDate>Fri, 11 Nov 2011 19:50:02 +0000</pubDate>
		<dc:creator>todd anderson</dc:creator>
				<category><![CDATA[AIR]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Flex 4]]></category>
		<category><![CDATA[Flex 4.5]]></category>

		<guid isPermaLink="false">http://custardbelly.com/blog/?p=502</guid>
		<description><![CDATA[Thought i would share a little gist with you about a solution i whipped up with regards to deferred content in a Flex 4 Group container. 
If there are numerous children within a container and their style definitions are rather complex, there may be some lag within the rendering cycle. Though it may not cause [...]]]></description>
			<content:encoded><![CDATA[<p>Thought i would <a href="https://gist.github.com/1340472" target="_blank">share a little gist</a> with you about a solution i whipped up with regards to deferred content in a Flex 4 <strong>Group</strong> container. </p>
<p>If there are numerous children within a container and their style definitions are rather complex, there may be some lag within the rendering cycle. Though it may not cause the <strong>Flash Player</strong> to time-out or even invoke the beachball/hourglass of the user&#8217;s system, any perceived lag in rendering that is a considerable amount (to be discussed at a later date) could send the user packing if not in the very least curious as to the reliability of the application; needless to say, most UI heavy applications are those in which a user interacts heavily with the application in order to get something accomplished.</p>
<p>Setting UX/design decisions aside and trusting that optimizations &#8211; such as absolute positioning &#8211; are being used where appropriate, there still may come a time where the task at hand calls for a lengthly child list within a container, or even a rather small list with a heavy render cycle due to customization. In such a situation, having the ability to defer rendering is a great improvement to the perceived &#8220;snappiness&#8221; of your application.</p>
<p>Back in the Flex 3 days &#8211; well, i shouldn&#8217;t say &#8220;back&#8221; as the <strong>MX</strong> containers are still available in the SDK and i am sure there are still people working on Flex 3 whether grudgingly or not &#8211; the <strong>MX</strong> containers had a property called <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/core/Container.html#creationPolicy" target="_blank"><em>creationPolicy</em></a>. This allowed a developer to define the how the container was to render its children &#8211; basically, whether it should build its display tree upon creation of the container or defer. If you deferred it by setting the property to <em>ContainerCreationPolicy.NONE</em>, you could at anytime within the life of the application call <em>createComponentsFromDescriptors()</em> on that container to have its children be created.</p>
<p>Now it should be noted that this functionality is at parity in Flex 4.x, yet only available to <strong>SkinnableContainers</strong> &#8211; and more accurately those that implement <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/core/IDeferredContentOwner.html#propertySummary" target="_blank"><strong>IDeferredContentOwner</strong></a>. Those containers within the Flex 4 SDK which are considered lighter-weight, such as <strong>Group</strong> and <strong>DataGroup</strong>, do not play host to skins or define style properties for graphical backgrounds but they also do not support deferred content inherently either.</p>
<p>I should stop here and say that even though <strong>Group</strong> and <strong>DataGroup</strong> are in the same boat as not being privy to a <em>creationPolicy</em>, the example code should really only be translated to a <strong>Group</strong> container. Deferred content for a <strong>DataGroup</strong> should be left to its defined layout and its properties. That said, there is a way to defer the child element creation of a <strong>Group</strong> rather simply; that is by utilizing the <strong>[DefaultProperty]</strong> metadata.</p>
<p>You can see the full <a href="https://gist.github.com/1340472" target="_blank">gist of the moving pieces on my github</a>, but just to give a quick example and rundown:</p>
<pre class="brush: jscript; first-line: 1; title: ;">
package
{
    import flash.events.Event;

    import mx.events.FlexEvent;

    import spark.components.Group;

    /**
     * Use the deferredElements property as the modifier that is handed the list of IVisualElements defined in MXML.
     */
    [DefaultProperty(&quot;deferredElements&quot;)]

    /**
     * Group container extension in order to do deferred child element attachment.
     */
    public class DeferredGroup extends Group
    {
        protected var _elementAddQuota:int = 10;

        /* IVisualElement[] */
        protected var _deferredElements:Array;
        protected var _deferredElementsChanged:Boolean;

        protected var _deferredElementAttacher:IDeferredElementAttacher;

        public function DeferredGroup()
        {
            super();
        }

        /**
         * @inheritDoc
         */
        override protected function commitProperties():void
        {
            super.commitProperties();
            if( _deferredElementsChanged )
            {
                queueDeferredElements();
                _deferredElementsChanged = false;
            }
        }

        /**
         * Defines and executes the IDeferredElementAttacher implementation used in queue-ing up &quot;packs&quot;
         * of IVisualElement instances declared in MXML and assigned as deferredElements.
         */
        protected function queueDeferredElements():void
        {
            // Define IDeferredElementAttacher and listen for completion on attach of all elements within deferredElements.
            _deferredElementAttacher = new FrameDeferredElementAttacher( this );
            _deferredElementAttacher.addEventListener( Event.COMPLETE, handleDeferredAttachmentComplete, false, 0, true );

            // &quot;Chunk&quot; up lists of IVisualElements based on limit quota.
            var i:int;
            var startIndex:int;
            var endIndex:int;
            var length:int = _deferredElements.length;
            var count:int = Math.ceil(length / _elementAddQuota);
            for( i = 0; i &lt; count; i++ )
            {
                startIndex = i * _elementAddQuota;
                endIndex = startIndex + _elementAddQuota;
                endIndex = ( endIndex &gt; length ) ? length : endIndex;
                _deferredElementAttacher.addElementPack( _deferredElements.slice( startIndex, endIndex ) );
            }
            _deferredElementAttacher.start();
        }

        /**
         * Event handler for completion from the IDeferredElementAttacher instance.
         * @param evt Event
         */
        protected function handleDeferredAttachmentComplete( evt:Event ):void
        {
            // Kill reference.
            _deferredElementAttacher.removeEventListener( Event.COMPLETE, handleDeferredAttachmentComplete, false );
            _deferredElementAttacher.dispose();
            _deferredElementAttacher = null;

            // -&gt; Do whatever you normally would do in a handler for CREATION_COMPLETE.
        }

        /**
         * The amount of IVisualElements to &quot;chunk&quot; into packets for deferred queue.
         * @return int
         */
        public function get elementAddQuota():int
        {
            return _elementAddQuota;
        }
        public function set elementAddQuota( value:int ):void
        {
            _elementAddQuota = value;
        }

        /**
         * The DefaultProperty array of IVisualElements declared in MXML markup.
         * @return Array Required to be IVisualElement[]
         */
        public function get deferredElements():Array
        {
            return _deferredElements;
        }
        public function set deferredElements( value:Array ):void
        {
            if( _deferredElements == value ) return;

            _deferredElements = value;
            _deferredElementsChanged = true;
            invalidateProperties();
        }
    }
}
</pre>
<p>Essentially, I have defined the <strong>[DefaultProperty]</strong> to be the <em>deferredElements</em> property. By default, any Flex container&#8217;s <strong>[DefaultProperty]</strong> is the <em>mxmlContent</em> property. If left to default, anything declared in MXML within the container declaration is handed to the <em>mxmlContent</em> property which in turn is used to add the children to the container using ActionScript at a later time within its instantiation cycle. Just as an example, the <strong>Label</strong> and <strong>Button</strong> of the <strong>Group</strong> container defined in this MXML can be considered the array of <strong>IVisualElements</strong> known to the parent <strong>Group</strong> as <em>mxmlContent</em>.</p>
<pre class="brush: xml; first-line: 1; title: ;">
&lt;s:Group&gt;
    &lt;s:Label text=&quot;Hello, World&quot; /&gt;
    &lt;s:Button label=&quot;foo&quot; /&gt;
&lt;/s:Group&gt;
</pre>
<p>&#8230; and same goes for Flex 3 containers. Not much has changed, aside form non-parity in <em>creationPolicy</em> on Flex 4 containers that don&#8217;t implement <strong>IDeferredContentOwner</strong>. However, in the example provided above and in the <a href="https://gist.github.com/1340472" target="_blank">gist</a>, the declared children in MXML aren&#8217;t handed to the <em>mxmlChildren</em>, but rather the <em>deferredChildren</em>. Because of this, we can then check if we have deferred content upon a pass to <em>invalidationProperties()</em> and act accordingly &#8211; as is done by invoking <em>queueDeferredElements</em>() in the example:</p>
<pre class="brush: jscript; first-line: 48; title: ;">
/**
 * Defines and executes the IDeferredElementAttacher implementation used in queue-ing up &quot;packs&quot; of IVisualElement instances declared in MXML and assigned as deferredElements.
 */
protected function queueDeferredElements():void
{
    // Define IDeferredElementAttacher and listen for completion on attach of all elements within deferredElements.
    _deferredElementAttacher = new FrameDeferredElementAttacher( this );
    _deferredElementAttacher.addEventListener( Event.COMPLETE, handleDeferredAttachmentComplete, false, 0, true );

    // &quot;Chunk&quot; up lists of IVisualElements based on limit quota.
    var i:int;
    var startIndex:int;
    var endIndex:int;
    var length:int = _deferredElements.length;
    var count:int = Math.ceil(length / _elementAddQuota);
    for( i = 0; i &lt; count; i++ )
    {
        startIndex = i * _elementAddQuota;
        endIndex = startIndex + _elementAddQuota;
        endIndex = ( endIndex &gt; length ) ? length : endIndex;
        _deferredElementAttacher.addElementPack( _deferredElements.slice( startIndex, endIndex ) );
     }
     _deferredElementAttacher.start();
}
</pre>
<p>And in that method, an <strong>IDeferredElementAttacher</strong> (non-SDK, part of the <a href="https://gist.github.com/1340472" target="_blank">gist</a>) implementation is used to queue up smaller arrays of child elements and dequeued to start adding children to the target container. In this example that implementation is a <strong>FrameDeferredElementAttacher</strong> instance which waits a frame to move along in its queue. Included in the <a href="https://gist.github.com/1340472" target="_blank">gist</a> is also one for timer-based element addition.</p>
<p>This post got rather long as far as just wanting to show off how to defer child content of a <strong>Group</strong> container in Flex 4, but I just wanted to bring light my solution as there is no parity of <em>creationPolicy</em> on non-<strong>IDeferredContentOwner</strong> containers in the SDK.</p>
<p>See the whole gist here: <a href="https://gist.github.com/1340472">https://gist.github.com/1340472</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://custardbelly.com/blog/2011/11/11/deferred-content-for-flex-4-group-using-defaultproperty/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>massroute-js: dojo example</title>
		<link>http://custardbelly.com/blog/2011/10/04/massroute-js-dojo-example/</link>
		<comments>http://custardbelly.com/blog/2011/10/04/massroute-js-dojo-example/#comments</comments>
		<pubDate>Tue, 04 Oct 2011 13:46:08 +0000</pubDate>
		<dc:creator>todd anderson</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[dojo]]></category>
		<category><![CDATA[massroute-js]]></category>

		<guid isPermaLink="false">http://custardbelly.com/blog/?p=486</guid>
		<description><![CDATA[I have created a github repository at http://github.com/bustardcelly/massroute-js to explore various JavaScript libraries and frameworks with a focus of delivering a web-based application for real-time transportation data made available from MassDOT. This article intends to address my findings in an exploration of one of those libraries or frameworks that have caught my interest. If you [...]]]></description>
			<content:encoded><![CDATA[<p><em>I have created a github repository at <a href="http://github.com/bustardcelly/massroute-js" target="_blank">http://github.com/bustardcelly/massroute-js</a> to explore various JavaScript libraries and frameworks with a focus of delivering a web-based application for <a href="http://www.eot.state.ma.us/developers/realtime/" target="_blank">real-time transportation data made available from MassDOT</a>. This article intends to address my findings in an exploration of one of those libraries or frameworks that have caught my interest. If you have any suggestions for another <strong>JavaScript</strong> library/framework please leave a comment.</em></p>
<p><em>It should also be noted that some explanations may be heavily influenced by my experience in developing for the <strong>Flash Platform</strong> and particularly their relation to the <strong>ActionScript</strong> and the <strong>Flex</strong> mark-up language.</em></p>
<p>As far as <strong>JavaScript</strong> libraries that go beyond providing an abstraction layer/decorator to the <strong>DOM</strong> and a facade for <strong>AJAX</strong> requests &#8211; such as one would find with <a href="http://jquery.com" target="_blank">jQuery</a> &#8211; I have been interested in digging into <a href="http://dojotoolkit.org/" target="_blank">Dojo</a> for some time. I should state that I am in no way knocking <strong>jQuery</strong>. It works extremely well at what it purports to do. I do, however, have an interest in how to &#8220;maintain&#8221; an application written in <strong>JavaScript</strong> in as much as not only adhering to architectural patterns but code organization and dependency management. That is not to say you could not work with another library that incorporates or works laterally with <strong>jQuery</strong> for such support; I am also interested in those libraries that provide more of a unified application structure alongside <strong>AJAX</strong> and <strong>DOM</strong> access. Enough defending <strong>jQuery</strong>&#8230;</p>
<p>For many reasons <a href="http://dojotoolkit.org/" target="_blank">Dojo</a> caught my eye because not only does it provide <strong>DOM</strong> access/manipulation through abstraction (as well as using <a href="http://sizzlejs.com/" target=_blank">Sizzle</a> as the selector engine, as <strong>jQuery</strong> does) but dependency management through a modular package system, as well. What that really means is that I can organize my scripts in a directory tree structure, and define classes and their dependencies using the provide/declare/require API of <a href="http://dojotoolkit.org/" target="_blank">Dojo</a>. This allows for a common &#8220;package structure&#8221; and resolves to namespaced objects at runtime (or <em>build time</em>- maybe more on that later), providing a modular-approach to building a <strong>JavaScript</strong> application.</p>
<p><em>The example was built against <strong>Dojo 1.6.1</strong>, so any further explanations in this post are dependent on my knowledge working with the Dojo library at that version.</em></p>
<h2>Modules</h2>
<p>Now, truth be told, I utilized the <strong>Dojo</strong> module dependency system as I would with declaring and importing classes. This is mainly because of my experience with languages that are class-based (or provide a class &#8220;structure&#8221;) and that <strong>Dojo</strong> provides an elegant and easy way for class declaration and inheritance on top of the prototypical nature of <strong>JavaScript</strong>. So my modules really became more like classes or groupings of common classes &#8211; which is perfectly acceptable to me and how I would prefer to work &#8211; but it should be noted (if you were to look at <a href="htts://github.com/bustardcelly/massroute-js" target="_blank">the example in the github repo</a>) that modules are not restricted to only declaring classes.</p>
<p>Just to provide a quick example of what i mean by treating modules as independent classes or a grouping of common classes, let&#8217;s look at an abbreviated version of the main context module (script file) for the application:</p>
<pre class="brush: jscript; first-line: 1; title: ;">
dojo.provide( &quot;context.massroute&quot; );
dojo.require( &quot;model.session&quot; );

dojo.declare( &quot;context.massroute.MassRouteContext&quot;, null, {
    constructor: function() {
        this.session = new model.session.Session();
    }
}
</pre>
<p>The value within a <em>dojo.provide()</em> invocation creates (if not previously existant) a namespaced object on global (window) scope and caches the reference within <em>dojo._loadedModules</em> with the property value of the string argument (&#8221;context.massroute&#8221; in this example). Essentially this sets up a &#8220;package&#8221; structure for your declarations with access to classes once a module has been requested and loaded. </p>
<p>Modules are loaded using<em> dojo.require()</em>. The <em>dojo.require()</em> states a dependency on another module. For this example, <strong>Dojo</strong> is requested to load the &#8220;model.session&#8221; module. More on the association between files and package declarations in a bit, but for now know that if &#8220;model.session&#8221; is not found on the <em>dojo._loadedModules</em> cache, a request for <strong>/model/session.js</strong> will be made. Once loaded, it would go through much of what is currently being covered in this example: defining namespace, loaded dependencies and declaring classes. If we were to open the <strong>/model/session.js</strong> file found the application script source, we would find a <em>dojo.declare()</em> for the <strong>model.session.Session</strong> class.</p>
<p>With each <em>dojo.declare()</em> within the provided namespace, the objects on the direct global scope and within <em>dojo._loadedModules</em> are updated to hold reference to the class, which essentially allows you to create a new instance of a class as one normally would:</p>
<pre class="brush: jscript; first-line: 1; title: ;">
var context = new context.massroute.MassRouteContext();
</pre>
<p>// declare explanation<br />
The <em>dojo.declare()</em> takes three arguments:</p>
<ul>
<li>className: defines the associated name for the class within the package/namespace.</li>
<li>inheritance: defines the classes to &#8220;mixin&#8221; to your class. This can be null, a single class reference or an array of class references. The class reference(s) can be thought of as base or multiple inheritance if defined.</li>
<li>properties: defines the object that encapsulates all the logic particular to the class</li>
</ul>
<p><em>The inheritance I found of particular note as dojo provides an easy way to call super methods. Essentially, within the scope of the override method of a subclass you can call this.inherited(arguments).</em></p>
<p>To get a better understanding of how this all works and what is modified as modules are loaded and classes declared, if we suppose that this module is requested to be loaded in the current domain, the global object will be modified to reflect the following:</p>
<pre class="brush: jscript; title: ;">
[window] {
    dojo: {
        _loadedModules: {
            &quot;context.massroute&quot;: {
                &quot;MassRouteContext&quot;: function() { ... };
            }
            &quot;model.session&quot;: {
                &quot;Session&quot;: function() { ... };
            }
        }
    }
    context: {
        massroute: {
            MassRouteContext: function() { ... };
        }
    }
    model: {
        session: {
            Session: function() { ... };
        }
    }
}
</pre>
<p>That gives a little insight into <strong>Dojo</strong>&#8217;s nested namespace pattern and how access to classes is provided, as well as how <strong>Dojo</strong> manages caching of previously requested dependencies.</p>
<p>Just for kicks, if we translated this example over to ActionScript it would be read as this:</p>
<pre class="brush: jscript; first-line: 1; title: ;">
package context.massroute {
    import model.session.Session;

    class MassRouteContext {
        public var session:Session;

        function MassRouteContext() {
            session = new Session();
        }
    }
}
</pre>
<p>I touched on it briefly before, but you may be wondering how dojo knows how to associated these namespaces with modules to load within its package system. By default, <strong>Dojo</strong> will assume that a file with the name of the ending namespace resides in a relative location of its request &#8211; meaning, if my main <strong>index.html</strong> file resides at the root of the directory, when I <em>dojo.require(&#8221;context.massroute&#8221;)</em>, <strong>dojo</strong> will make a request for <strong>./context/massroute.js</strong> if the path to that module is not defined. If you have taken a look at the example in my github repo, you may notice that <strong>/content/massroute.js</strong> is not located at the root but in a parenting directory describing the scripts for my application.</p>
<p>You can define the path to your modules by declaring a global <em>dojoConfig</em> object prior to load of the <strong>Dojo</strong> library. An abbreviated version of what that would be for the example above:</p>
<pre class="brush: xml; first-line: 22; title: ;">
&lt;script&gt;
    dojoConfig = {
      baseUrl: './',
      modulePaths : {
            app : &quot;js/app&quot;,
            context: &quot;js/app/context&quot;,
            model: &quot;js/app/model&quot;
        }
    };
&lt;/script&gt;
&lt;script src=&quot;http://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojo/dojo.xd.js&quot;&gt;&lt;/script&gt;
</pre>
<p>This defines the base URL for the directories defined in <strong>modulePaths</strong>. Now when you <em>dojo.require( &#8220;context.massroute&#8221; )</em>, <strong>dojo</strong> will look up the associated directory for the context namespace and request to load <strong>massroute.js</strong>. Once loaded, it is important to note that the file isn&#8217;t inserted into a script tag which is a common practice for script loaders. It is actually run through <em>dojo.eval()</em> which creates namespaced objects on  <strong>global</strong> and <strong>dojo</strong> scopes as described above.</p>
<h3>Some Caveats</h3>
<p>There are some things that I didn&#8217;t immediately realize or think of off-hand that may be of interest to those of you whether or not you come from a class-based language:</p>
<ul>
<li>Anything you think is defined privately to the &#8220;class&#8221; in the constructor using <em>dojo.declare()</em> is actually set at global scope.</li>
<li>No such things as private members to the class. Prepending members with &#8220;<strong>_</strong>&#8221; is the convention to &#8220;convey&#8221; to developers that a member is private.</li>
</ul>
<p>There is a way around this whole private member business, however. If you are in dire need to keep something private, you can use an <a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/" target="_blank">Immediately Invoked Function Expression</a> (<strong>IIFE</strong>) to define your private members as well as the class, such as:</p>
<pre class="brush: jscript; first-line: 1; title: ;">
dojo.provide( &quot;context.massroute&quot; );
dojo.require( &quot;model.session&quot; );

(function() {
    var _session = new model.session.Session();
    dojo.declare( &quot;context.massroute.MassRouteContext&quot;, null, {
        constructor: function() {
            console.info( _session );
        }
    }
}
)();
</pre>
<p>It should also be noted that you don&#8217;t have to use <em>dojo.declare()</em> at all to get the same structure. Essentially &#8211; from what I gather &#8211; under the hood, the library does the following (in as far as constructing the namespace) which you are perfectly welcome to do as well in a module and can help with your private requirements using a mix of <strong>IIFE</strong> and the <a href="http://javascript.crockford.com/private.html" target="_blank">Constructor Pattern</a>:</p>
<pre class="brush: jscript; first-line: 1; title: ;">
dojo.require( &quot;model.session&quot;);

(function() {
    if( !dojo._hasResource[&quot;context&quot;] ) {
        dojo._hasResource[&quot;context&quot;] = true;
        dojo.context = {};
    }
    if( !dojo._hasResource[&quot;context.massroute&quot;] ) {
        dojo._hasResource[&quot;context.massroute&quot;] = true;
        dojo.provide( &quot;context.massroute&quot; );

        context.massroute.MassRouteContext = function() {
            var _session = new model.session.Session();
            return {
                getSession: function() {
                    return _session;
                }
            }
        }
    }
})();
</pre>
<p>Obviously, going that route, you will miss the niceties that <strong>Dojo</strong> provides in class inheritance but just throwing it out there.</p>
<h2>Events</h2>
<p><strong>Dojo</strong>&#8217;s event system was another part of the framework i enjoyed. Using <em>dojo.connect()</em> and <em>dojo.disconnect()</em> you could easily assign and remove event handling (delegate functions) to <strong>DOM</strong> events on a target scope, respectively. And, because <em>dojo.connect()</em> returned a connect object, it conveniently made it possible to disconnect all connection I may have set up in a view controller that was going to be trashed:</p>
<pre class="brush: jscript; title: ;">
var connections = [];
connections.push( dojo.connect( dojo.byId('submitButton'), 'onclick', handleSubmitRequest ) );
connections.push( dojo.connect( dojo.byId('cancelButton'), 'onclick', handleCancelRequest ) );
...
dojo.forEach( connections, dojo.disconnect );
</pre>
<p>It should be noted that when using <em>dojo.connect()</em> you are not limited to just <strong>DOM</strong> events. You can connect to &#8220;custom&#8221; events on non-<strong>DOM</strong> objects. To do so, the second argument is actually the function on the target object that you wish to &#8220;listen&#8221; for invocation of. As a quick example:</p>
<pre class="brush: jscript; first-line: 1; title: ;">
var test = function() {
    return {
        run: function() {
            setTimeout( this.onTimeout, 1000 );
        },
        onTimeout: function() {
            console.info( &quot;test.onTimeout&quot; );
        }
    }
};

var myTest = new tester();
dojo.connect( myTest, &quot;onTimeout&quot;, function() {
    console.info( &quot;dojo.connect() &gt; onTimeout&quot; );
});
myTest.run();
</pre>
<p>Along with <em>dojo.connect()</em> and <em>dojo.disconnect()</em>, using <em>dojo.publish()</em> and <em>dojo.subscribe()</em>/<em>dojo.unsubscribe()</em> you can make use of the global event bus to broadcast and subscribe to custom events &#8211; similar to, say, the <em>NSNotificationCenter</em> from <strong>Objective-C</strong>. I used this heavily in reporting what i deemed application-level state related events from the view controllers in the <strong>Dojo</strong> example in the <a href="http://github.com/bustardcelly/massroute-js" target="_blank">massroute-js github repo</a>, and thought it was a pleasure to work with.</p>
<h2>Other</h2>
<p>Just quick notes on some other things that i found interesting from the <strong>Dojo</strong> framework that I either used or want to use in the future using <strong>Dojo</strong>:</p>
<h3>dojo.hitch</h3>
<p>Keeping scope was a pleasure with <em>dojo.hitch()</em>. Due to developer requirements from <strong>MassDOT</strong> in using their <strong>API</strong> for real-time transportation data, you cannot make <strong>API</strong> calls more frequently than every 10 seconds. This meant that I had to implement a request queue in which I had to route the calls: immediate invoke if timer not running, else your next in line when timer runs out. Keeping scope of what was to be called when inside this queue manager was necessary as the queue manager itself was not supposed to have any logic about the service, only knowledge of state between orders coming and going. So it was important that when it was time to process the order, the scope was tied to the one who placed the order.<br />
<a href="http://dojotoolkit.org/reference-guide/dojo/hitch.html" target="_blank">dojo reference: dojo.hitch()</a></p>
<h3>dojo.behavior</h3>
<p>Though I went with my own custom view controllers and their logic encapsulated in respective classes, Dojo provides the ability to assign &#8220;behaviors&#8221; which i really want to look into further as it looks to be a nice design in separation of logic from view using mediation that can be swapped out quite easily at runtime.<br />
<a href="http://dojotoolkit.org/documentation/tutorials/1.6/using_behavior/" target="_blank">dojo toolkit: Using dojo.behaviour</a></p>
<h2>Wish I Coulda</h2>
<p>The following are a couple things I struggled with when working with the <strong>Dojo</strong> toolkit.</p>
<h3>Development/Debugging</h3>
<p>I love <strong>breakpoints</strong>. Being able to set a breakpoint and traverse a call stack and inspect properties is the pleasurable way for me to debug any problems. However, due to the design of <strong>Dojo</strong>&#8217;s modular architecture I found myself relying more on console for debugging purposes as modules are essentially read from a URL and evaluated as an expression. This means i couldn&#8217;t locate the file resource in development tools and set a breakpoint in any of my modules. </p>
<p>I am sure there is some trick or project set-up that would provide a more debugging-friendly environment when developing an application with <strong>Dojo</strong>, but I couldn&#8217;t find it. If you know of one, please leave a comment. </p>
<h3>Build</h3>
<p>From the looks of it, <strong>Dojo</strong> has a pretty powerful <a href="http://dojotoolkit.org/reference-guide/build/" target="_blank">Build System</a>. Intended to produce minified and concatenated scripts, using the build system allows you to package only what your app required from the <strong>Dojo</strong> framework. I frustratingly tried to get it to work a couple times, but it always ended up with the full dojo and my scripts were never minified or concatenated and it created this weird directory structure that made no sense. I am probably doing it wrong, but there is little out there in documentation if anything goes wrong. </p>
<p>There is also the <a href="http://build.dojotoolkit.org/" target="_blank">online Build Tool</a>, but i didn&#8217;t know the whole breath of source I needed for my build; I am assuming from the docs that there is where the power of the Build System and profiles comes into play.. Something I would definitely like to check out further because, next to the modular design, this *in theory* makes <strong>Dojo</strong> a real winner.</p>
<h2>Conclusion</h2>
<p>All in all, I was pretty impressed by <strong>Dojo</strong> and would recommend trying it out and may bring it up as a framework of choice for any larger projects in the future (especially if i could get Build to work for me). There was a slight learning curve mainly in the class declaration and inheritance design, but nothing over-daunting and actually quite revealing. The curve probably would have been higher if I was not already familiar with popular <strong>JavaScript</strong> patterns.</p>
<p><a href="http://dojotoolkit.org/">Dojo Toolkit</a><br />
<a href="https://github.com/bustardcelly/massroute-js/tree/master/massroute-examples/dojo">massroute-js/dojo</a></p>
]]></content:encoded>
			<wfw:commentRss>http://custardbelly.com/blog/2011/10/04/massroute-js-dojo-example/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>new github repo: massroute-js</title>
		<link>http://custardbelly.com/blog/2011/09/27/new-github-repo-massroute-js/</link>
		<comments>http://custardbelly.com/blog/2011/09/27/new-github-repo-massroute-js/#comments</comments>
		<pubDate>Tue, 27 Sep 2011 09:08:49 +0000</pubDate>
		<dc:creator>todd anderson</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jquery-mobile]]></category>

		<guid isPermaLink="false">http://custardbelly.com/blog/?p=483</guid>
		<description><![CDATA[This is just a quick post to alert any subscribers to this blog that are interested in JavaScript development that I created a repository some time back on github that holds my exploration of various JavaScript frameworks and libraries. You can check it out at http://github.com/bustardcelly/massroute-js.
Centered around the theme of developing a web-based application to [...]]]></description>
			<content:encoded><![CDATA[<p>This is just a quick post to alert any subscribers to this blog that are interested in JavaScript development that I created a <a href="https://github.com/bustardcelly/massroute-js" target="_blank">repository some time back on github</a> that holds my exploration of various JavaScript frameworks and libraries. You can check it out at <a href="https://github.com/bustardcelly/massroute-js" target="_blank">http://github.com/bustardcelly/massroute-js</a>.</p>
<p>Centered around the theme of developing a web-based application to access real-time MBTA transportation data (made available by <a href="http://www.twitter.com/MassDOTdev" target="_blank">MassDOT</a> &#8211; <a href="http://www.eot.state.ma.us/developers/realtime/" target="_blank">more info here</a>), I wanted to explore various libraries and micro-application frameworks that are out in-the-wild for JavaScript; some more well-known than others, but still hold my interest.</p>
<p>The initial commit included the work i had done with jQuery Mobile, which i have been actively working with for almost a year and have given a couple <a href="http://www.slideshare.net/todd_anderson/jquery-mobile-progressive-enhancement-with-html5-8302294" target="_blank">presentation</a>s on. Most recently, I committed an example of my exploration into <a href="http://dojotoolkit.org/" target="_blank">dojo</a>. I rather enjoyed working with the dojo framework and toolkit and hope to have another post that spotlights my experience working with it &#8211; actually i hope to post on each library/framework that i dig into with the repo, so we&#8217;ll see how that goes. Next up on my curiosity list is <a href="http://knockoutjs.com/" target="_blank">Knockout</a>&#8230;</p>
<p>I won&#8217;t list all those that have caught my eye, so if you have any suggestions please feel free to leave them in the comments.</p>
<p><strong>[Disclaimer]</strong><br />
If you look at the source of the examples in the repo, I don&#8217;t claim to be a master of the library or frameworks I am exploring, needless to say the JavaScript language itself. So, if you see something that is considered bad practice or all together wrong, please let me know.</p>
]]></content:encoded>
			<wfw:commentRss>http://custardbelly.com/blog/2011/09/27/new-github-repo-massroute-js/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AIR Native Extension Example: iBattery for iOS</title>
		<link>http://custardbelly.com/blog/2011/09/21/air-native-extension-example-ibattery-for-ios/</link>
		<comments>http://custardbelly.com/blog/2011/09/21/air-native-extension-example-ibattery-for-ios/#comments</comments>
		<pubDate>Wed, 21 Sep 2011 16:54:58 +0000</pubDate>
		<dc:creator>todd anderson</dc:creator>
				<category><![CDATA[AIR]]></category>
		<category><![CDATA[AS3]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Flex 4.5]]></category>
		<category><![CDATA[Native Extension for Adobe AIR]]></category>

		<guid isPermaLink="false">http://custardbelly.com/blog/?p=474</guid>
		<description><![CDATA[Introduction
The most exciting new feature coming to Adobe AIR to me is the ability to compile against a library that can communicate with a device natively. Though some of the Stage* API opens a whole new world of rendering improvements, the inclusion of Native extensions for Adobe AIR (NE) relieves the wishing and waiting of [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>The most exciting new feature <a href="http://blogs.adobe.com/flashplatform/2011/09/announcing-flash-player-11-and-air-3.html" target="_blank">coming to Adobe AIR</a> to me is the ability to compile against a library that can communicate with a device natively. Though some of the Stage* API opens a whole new world of rendering improvements, the inclusion of <a href="http://www.adobe.com/devnet/air/articles/extending-air.html" target="_blank">Native extensions for Adobe AIR</a> (NE) relieves the wishing and waiting of what will be exposed at the device level in future <strong>AIR SDK</strong> releases; we can now extend the <strong>Runtime</strong> ourselves. With the arrival of <strong>Native extensions</strong>, the possibilities of what can be achieved with a mobile <strong>AIR</strong> application grow larger; and certainly with that, so does complexity in design and the requirement to develop with mobile performance in mind. </p>
<p>Keeping the complexities and performance in check (and to calm myself down from excitement of the endless possibilities) I decided to give it a quick test-run by creating a <strong>Native Extension</strong> that I thought was sorely missing from the <strong>Adobe AIR SDK</strong> &#8211; battery information on iOS. In all seriousness, getting up and running and accessing the battery information of my iPhone from an application <strong>AIR</strong> application was rather painless and &#8211; dare i say it &#8211; easier than i expected. I intend to give a quick walk through of how I went about creating the <strong>iBattery Native Extension</strong> and how to use it in an AIR application.</p>
<h3>Disclaimer</h3>
<p>I am going to assume you are familiar with setting up an <strong>Apple Developer</strong> account and downloading the SDK and won&#8217;t even go into the headache of provisioning profiles and the deployment process for an <strong>iOS</strong> application. I am also going to assume that you are familiar with using the recent <strong>Flex 4.5 SDK</strong> to create mobile Flex applications. The application in this example is in no way complex, but I am not going to cover how the pieces of the application work &#8211; only how you can compile against and include an <strong>Native extension for Adobe AIR</strong>.</p>
<h3>Source</h3>
<p>If you are curious or just want to jump to code, I created a <a href="https://github.com/bustardcelly/iBattery" target="_blank">github repo</a> with all the source as well as deployment builds or if you just came here for the <strong>Native Extension</strong> and know your way around you can download <a href="http://www.custardbelly.com/downloads/air/ane/ibatteryextension.ane.zip">ibatteryextension.ane</a> directly.</p>
<h2>Requirements</h2>
<ul>
<li><a href="http://opensource.adobe.com/wiki/display/flexsdk/Download+Flex+4.5" target="_blank">Flex 4.5.1 SDK</a></li>
<li><a href="http://labs.adobe.com/technologies/flashplatformruntimes/air3/" target="_blank">AIR 3 Runtime and SDK (Release Candidate)</a></li>
<li><a href="http://developer.apple.com/devcenter/ios/index.action" target="_blank">iOS SDK</a></li>
</ul>
<p>Also, take a look at these excellent articles:</p>
<ul>
<li><a href="http://www.adobe.com/devnet/air/articles/extending-air.html" target="_blank">Extending Adobe AIR by Oliver Goldman</a></li>
<li><a href="http://renaun.com/blog/2011/09/why-native-extensions-for-air/" target="_blank">Why Native Extensions for AIR</a></li>
<li><a href="http://www.adobe.com/content/dam/Adobe/en/devnet/devices/pdfs/DevelopingActionScriptExtensionsForAdobeAIR.pdf" target="_blank">Developing ActionScript Extensions for Adobe AIR</a></li>
<li><a href="http://www.adobe.com/devnet/air/native-extensions-for-air.html" target="_blank">Native Extensions for Adobe AIR</a> in the AIR Developer Center</li>
</ul>
<p><em>I am not going to cover how to get this going with any IDEs (eg. <strong>Flash Builder 4.5</strong>). I will show you how to do all this from the command line. There are some niceties with IDEs that will separate you from invoking the command line tools of the <strong>SDK</strong> directly, but sometimes it is nice to see what is going on behind the scenes.</em></p>
<p>I went about downloading the <strong>Flex 4.5 SDK</strong> and unzipping it somewhere on my local disk, then downloaded the <strong>Adobe AIR SDK</strong> and overlaid it on the <strong>Flex SDK</strong> using the instructions here: <a href="http://kb2.adobe.com/cps/495/cpsid_49532.html" target="_blank">How To Overlay the AIR SDK</a>. For the purposes of the examples in this article let&#8217;s just say that <strong>SDK</strong> is located on my machine at: <strong>/Users/todd/SDKs/flex_4.5_air_3rc1</strong>.</p>
<p>The whole iOS &#038; Xcode set up, you are on your own. Sorry, not to be mean. There is some great information already out there and i want to keep this article more focused on <strong>Native Extensions for Adobe AIR</strong> and not to prevent hair-loss developing for iOS.</p>
<h2>Moving Pieces</h2>
<p>There are three major portions to create an AIR application utilizing the <strong>Native Extension for Adobe AIR</strong>:</p>
<ol>
<li>Native code compiled for target platform.</li>
<li>Flex library project to deploy the Native Extension for Adobe AIR.</li>
<li>Mobile AIR application.</li>
</ol>
<p>Depending on your target device/platform, the language and generated library on the native-side can vary and really is covered well in <a href="http://www.adobe.com/devnet/air/articles/extending-air.html#articlecontentAdobe_numberedheader_4" target="_blank">Oliver Goldman&#8217;s article</a>. For the purposes of this example, the native part involved me writing some C/Obj-C and creating a static library (.a file). The Flex library project is actually two-fold; I created a library that interfaced with the <a href="http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/flash/external/ExtensionContext.html " target="_blank">flash.external.ExtensionContext</a>, then generated an <strong>.ane</strong> file from the <strong>SWC</strong> and static library. The <strong>Mobile AIR</strong> application is then compiled against this <strong>Native Extension</strong> and the <strong>.ane</strong> library file is included in the generated <strong>.ipa</strong> file.</p>
<h2>Native</h2>
<p>I am not that much of an C/Objective-C developer. I have developed and deployed a handful of iOS applications in the past (some reaching the <strong>AppStore</strong>), but honestly have not touched it in quite some time. So I have some history, but cannot speak at length on how things work and why. Let&#8217;s just say, for the example in this article, that I knew enough to get in and get out and carry on on the <strong>ActionScript</strong> side of things.</p>
<p>When creating a native extension targeting the iOS platform, you&#8217;ll write some C code (which can call Obj-C) and deploy a static library with a <strong>.a</strong> extension. What i did was create a new Library project in Xcode, imported the header file included with the <strong>AIR SDK</strong> (found at <strong>/include/FlashRuntimeExtensions.h</strong>) and added a <strong>.m</strong> (Obj-C implementation) file to the project that will serve as the implementation of the native context and expose the API for accessing the battery life and information of the iOS device:</p>
<pre class="brush: cpp; first-line: 1; title: ;">
// Access battery life.
FREObject GetBatteryLife(FREContext ctx, void* funcData, uint32_t argc, FREObject argv[]) {
    UIDevice *device = [UIDevice currentDevice];
    [device setBatteryMonitoringEnabled:YES];
    float life = [device batteryLevel];

    FREObject retVal;
    FRENewObjectFromDouble( life, &amp;retVal );
    return retVal;
}

// Access info about battery
FREObject GetBatteryInfo(FREContext ctx, void* funcData, uint32_t argc, FREObject argv[]) {
    UIDevice *device = [UIDevice currentDevice];
    [device setBatteryMonitoringEnabled:YES];
    int info = [device batteryState];

    FREObject retVal;
    FRENewObjectFromInt32( info, &amp;retVal );
    return retVal;
}
</pre>
<p>Boiled down and abstracted in thinking on the <strong>ActionScript</strong> side of things, the API of this native library exposes two methods: <em>GetBatteryLife</em> and <em>GetBatteryInfo</em>. Each return a numerical value related to their context: a Number representing the percent of battery life left on the device and an Integer representing battery state, respectively. The relation of the Number value to percent is fairly straight-forward. The Integer returned from <em>[[UIDevice currentDevice] batteryState]</em> relates to the various &#8220;states&#8221; that the battery can be in, and they are:</p>
<ul>
<li>0 : Unknown</li>
<li>1 : Unplugged</li>
<li>2 : Charging</li>
<li>3 : Full</li>
</ul>
<p>The <strong>FREObject</strong> is covered more properly by <a href="http://www.adobe.com/devnet/air/articles/extending-air.html#articlecontentAdobe_numberedheader_4" target="_blank">Oliver Goldman in his article</a>, and I just blindly assume that the <a href="http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/flash/external/ExtensionContext.html ">ExtensionContext</a> of the <strong>AIR SDK</strong> knows how to interpret this value for me so I can cast as an <strong>ActionScript</strong> type and move on. We&#8217;ll see how that happens in the next section.</p>
<h2>The Native Extension</h2>
<p>The previous section lightly covered the native side of things and generated a static library file that will be used to compile an <strong>Native Extension</strong> (NE) library that will be used by an AIR application to access battery information of an iOS device it is deployed to. Creating the <strong>Native Extension</strong> file (.ane) is actually a two step process:</p>
<ol>
<li>Create a Flash library project compiled against AIR libraries and expose an API that interfaces with the native library through <a href="http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/flash/external/ExtensionContext.html " target="_blank">ExtensionContext</a>.</li>
<li>Use the ADT command line tool with to generate an .ane file compiled against the library SWC and the native library.</li>
</ol>
<p>The <a href="http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/flash/external/ExtensionContext.html " target="_blank">flash.external.ExtensionContext</a> from the <strong>AIR SDK</strong> is your main access point to the native library. Essentially, you create a new instance of an <strong>ExtensionContext</strong> using an ID defined in an extension descriptor file compiled into the <strong>Native Extension</strong>. For the <strong>iBattery Native Extension</strong>, this is what my extension descriptor file looks like:</p>
<pre class="brush: xml; first-line: 1; highlight: [2,7]; title: ;">
&lt;extension xmlns=&quot;http://ns.adobe.com/air/extension/2.5&quot;&gt;
  &lt;id&gt;com.custardbelly.ibattery&lt;/id&gt;
  &lt;versionNumber&gt;1&lt;/versionNumber&gt;
  &lt;platforms&gt;
    &lt;platform name=&quot;iPhone-ARM&quot;&gt;
            &lt;applicationDeployment&gt;
                &lt;nativeLibrary&gt;libAIRExtensionC.a&lt;/nativeLibrary&gt;
                &lt;initializer&gt;ExtInitializer&lt;/initializer&gt;
                &lt;finalizer&gt;ExtFinalizer&lt;/finalizer&gt;
            &lt;/applicationDeployment&gt;
        &lt;/platform&gt;
  &lt;/platforms&gt;
&lt;/extension&gt;
</pre>
<p>Highlighted in that snippet are some important bits. The <strong>id</strong> node value will be used to create a new <strong>ExtensionContext</strong> instance. The <strong>nativeLibrary</strong> node value is the native library created in the previous section. For this example, it is also of note that we have defined the <em>iPhone-ARM</em> platform as a target, as well. This extension descriptor file describes the association of id to native library that the <strong>ExtensionContext</strong> will look up upon instantiation. To create an <strong>ExtensionContext</strong>:</p>
<p><em>com.cusardbelly.air.extensions.battery.ios.Battery</em></p>
<pre class="brush: jscript; title: ;">
_extensionContext = ExtensionContext.createExtensionContext( &quot;com.custardbelly.ibattery&quot;, &quot;main&quot; );
</pre>
<p>&#8230; and then use the <strong>call</strong>() method to invoke the corresponding method exposed in the native library. For the purposes of the example in this article, and for the <strong>iBattery Native Extension</strong>, I basically exposed the same API that was on the native side:</p>
<p><em>com.cusardbelly.air.extensions.battery.ios.Battery</em></p>
<pre class="brush: jscript; title: ;">
public function getBatteryLife():Number
{
    return _extensionContext.call( 'GetBatteryLife' ) as Number;
}

public function getBatteryState():int
{
    return _extensionContext.call( 'GetBatteryInfo' ) as int;
}
</pre>
<p>With my API done, I compiled the library into a SWC:</p>
<pre class="brush: bash; title: ;">
&gt; /Users/todd/SDKs/flex_4.5_air_3rc1/bin/compc -output build/iBattery.swc -load-config+=ibattery_lib.config +configname=airmobile
</pre>
<p>If you are unfamiliar with using the command line tools of the SDK, I used the compc tool which is used to generate SWC files. The <strong>iBattery.swc</strong> file is generated and placed in a build directory and is compiled against an additional custom config (which just defines source location) and the <strong>+configname=airmobile</strong> directive. That&#8217;s actually a little fun tidbit. If you want to generate a SWC or SWF that uses the AIR mobile libraries, just add <strong>+configname=airmobile</strong> and they&#8217;ll be compiled against for you without defining them in an additional config file.</p>
<p>I then took the iBattery.swc and unzipped it to get the <strong>library.swf</strong> file. This is necessary for generating a <strong>Native Extension</strong> file (.ane) using the <strong>ADT</strong> command line tool:</p>
<pre class="brush: bash; title: ;">
&gt; /Users/todd/SDKs/flex_4.5_air_3rc1/bin/adt -package -target ane ../release/ibatteryextension.ane extension.xml -swc iBattery.swc -platform iPhone-ARM library.swf libAIRExtensionC.a
</pre>
<p>That generates an <strong>ibatteryextension.ane</strong> in a release directory and defines the target SWC library and platform as well as compiling in the descriptor, SWF library and native library.</p>
<p>That <strong>Native extension</strong> is then used as one would as SWC library in an AIR Mobile application to interface with the native library. You need to compile against the .ane and include it in an extension directory within the AIR application.</p>
<h2>The AIR Mobile Application</h2>
<p>The application I created to showcase the <strong>iBattery Native Extension</strong> is pretty dead simple. Again, I am assuming you have some knowledge of a mobile AIR application and its pieces. There are a ton of great articles out there that can help in developing an AIR application targeting mobile, so I won&#8217;t  provide any more explanations in this article, I just wanted to show you quickly how the communication works and the requirements for compilation of the application.</p>
<p>To being I just have a main <em>ViewNavigatorApplication</em> that defines a single view:</p>
<p><em>iBatteryExample.mxml</em></p>
<pre class="brush: xml; first-line: 1; title: ;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;s:ViewNavigatorApplication xmlns:fx=&quot;http://ns.adobe.com/mxml/2009&quot;
        xmlns:s=&quot;library://ns.adobe.com/flex/spark&quot;
        firstView=&quot;BatteryTestView&quot;&gt;

&lt;/s:ViewNavigatorApplication&gt;
</pre>
<p>&#8230; and the <em>BatteryTestView</em> provides a UI to request the battery information on the device and does all the communication through the <strong>ActionScript</strong> side of the <strong>Native Extension</strong> library generated previously:</p>
<p><em>BatteryTestView.mxml</em></p>
<pre class="brush: xml; first-line: 1; title: ;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;s:View xmlns:fx=&quot;http://ns.adobe.com/mxml/2009&quot;
        xmlns:s=&quot;library://ns.adobe.com/flex/spark&quot;
        title=&quot;BatteryTestView&quot; creationComplete=&quot;handleCreationComplete();&quot;&gt;

    &lt;fx:Script&gt;
        &lt;![CDATA[
            import com.custardbelly.air.extensions.battery.ios.Battery;

            protected var _batteryExtension:Battery;

            protected function handleCreationComplete():void
            {
                _batteryExtension = new Battery();

                lifeButton.addEventListener( MouseEvent.CLICK, handleLifeRequest, false, 0, true );
                infoButton.addEventListener( MouseEvent.CLICK, handleInfoRequest, false, 0, true );
            }

            protected function handleLifeRequest( evt:Event ):void
            {
                try {
                    console.appendText( &quot;Battery Life Percentage: &quot; );
                    console.appendText( ( _batteryExtension.getBatteryLife() * 100 ).toString() + &quot;%\n&quot; );
                }
                catch( e:Error )
                {
                    console.appendText( &quot;Error: &quot; + e.message );
                }
            }

            protected function handleInfoRequest( evt:Event ):void
            {
                console.appendText( &quot;Battery State: &quot; + ( _batteryExtension.getBatteryState() ).toString() + &quot;\n&quot; );
            }
        ]]&gt;
    &lt;/fx:Script&gt;

    &lt;s:layout&gt;
        &lt;s:VerticalLayout paddingLeft=&quot;10&quot; paddingRight=&quot;10&quot; paddingTop=&quot;10&quot; paddingBottom=&quot;10&quot; /&gt;
    &lt;/s:layout&gt;

    &lt;s:TextArea id=&quot;console&quot; width=&quot;100%&quot; height=&quot;100%&quot; editable=&quot;false&quot; text=&quot;Hello World!&quot; /&gt;
    &lt;s:HGroup width=&quot;100%&quot; height=&quot;24&quot; verticalAlign=&quot;middle&quot;&gt;
        &lt;s:Button id=&quot;lifeButton&quot; label=&quot;get life&quot; /&gt;
        &lt;s:Button id=&quot;infoButton&quot; label=&quot;get info&quot; /&gt;
    &lt;/s:HGroup&gt;

&lt;/s:View&gt;
</pre>
<p>Access to the <strong>ActionScript</strong> API from the <strong>Native Extension</strong> is available just as if you were developing against an external SWC library, and I created a new instance of a <em>Battery</em> to request life and information of the device which is then just printed out in a text area:</p>
<p><em>BatteryTestView.mxml</em></p>
<pre class="brush: jscript; first-line: 14; title: ;">
_batteryExtension = new Battery();
</pre>
<pre class="brush: jscript; first-line: 34; title: ;">
console.appendText( &quot;Battery State: &quot; + ( _batteryExtension.getBatteryState() ).toString() + &quot;\n&quot; );
</pre>
<p>To generate my AIR application for iOS, was a two step process. First, I generated the application SWF targeting AIR mobile:</p>
<pre class="brush: bash; title: ;">
&gt; /Users/todd/SDKs/flex_4.5_air_3rc1/bin/mxmlc +configname=airmobile -output build/iBatteryExample.swf src/iBatteryExample.mxml -load-config+=battery_app.config
</pre>
<p>Again i used the <strong>+configname=airmobile</strong> directive to include the mobile SWC from the Adobe AIR SDK without defining the dependencies in an additional config file. I did, however, have an additional config file that defined the <strong>Native Extension</strong> (.ane file) to compile against as an external library:</p>
<p><em>battery_app.config</em></p>
<pre class="brush: xml; first-line: 1; title: ;">
&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;flex-config xmlns=&quot;http://www.adobe.com/2006/flex-config&quot;&gt;
    &lt;compiler&gt;
        &lt;external-library-path append=&quot;true&quot;&gt;
            &lt;path-element&gt;ext/ibatteryextension.ane&lt;/path-element&gt;
        &lt;/external-library-path&gt;
    &lt;/compiler&gt;
&lt;/flex-config&gt;
</pre>
<p>That generated an <em>iBatteryExample.swf</em> which was then used alongside an application descriptor file to compile and generate the <strong>.ipa</strong> file (application installer file for iOS). We can create that using the <strong>ADT</strong> command line tool:</p>
<pre class="brush: bash; title: ;">
&gt; /Users/todd/SDKs/flex_4.5_air_3rc1/bin/adt -package -target ipa-test-interpreter -provisioning-profile {path.to}.mobileprovision -storetype pkcs12 -keystore {path.to}.developer_identity.p12 -storepass {pass} ../release/iBatteryExample.ipa iBatteryExample-app.xml iBatteryExample.swf -extdir ../ext/
</pre>
<p>There are two things in this command that you should note. First off, you will need to replace the <em>{path.to}</em> and <em>{pass}</em> tokens to point to your iOS developer files and password, respectively. Second is the <em>-extdir</em> option. This defines where the application can locate the <strong>Native Extension</strong> (.ane file).</p>
<p>And that was pretty much it for the application. Pretty basic, but a rather quick way to get up and running to allow someone to find information about their battery on an iOS device.</p>
<h2>Conclusion</h2>
<p>The addition of <strong>Native Extensions for Adobe AIR</strong> to the AIR SDK opens a lot of doors not only for native device integration but also to the experience you can provide in a mobile AIR application &#8211; with the biggest takeaway (as a developer) being that we no longer have to wait and see what gets exposed to us at the device-level in future <strong>AIR SDK</strong> releases. We can just write our own native extension now.</p>
<p>Hopefully this article provided some insight on how to quickly get up and running in creating your own Native Extensions and how to incorporate them into your mobile AIR application. And it should be noted that though this example was iOS specific, the native library for an <strong>Native Extension for Adobe AIR</strong> is in no way restricted to that platform and you should really check out <a href="http://www.adobe.com/devnet/air/articles/extending-air.html#articlecontentAdobe_numberedheader_4" target="_blank">Oliver Goldman&#8217;s excellent article, Extending Adobe AIR on the Adobe DevNet</a>.</p>
<p>The source discussed in this article can be found on <strong>github</strong> at <a href="https://github.com/bustardcelly/iBattery">http://github.com/bustardcelly/iBattery</a> and the <a href="http://www.custardbelly.com/downloads/air/ane/ibatteryextension.ane.zip" target="_blank">ibatteryextension.ane</a> itself (if you&#8217;d like to use it in your application) can be downloaded from this link.</p>
]]></content:encoded>
			<wfw:commentRss>http://custardbelly.com/blog/2011/09/21/air-native-extension-example-ibattery-for-ios/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Flex 4.5 Hidden Additions*</title>
		<link>http://custardbelly.com/blog/2011/07/15/flex-4-5-hidden-additions/</link>
		<comments>http://custardbelly.com/blog/2011/07/15/flex-4-5-hidden-additions/#comments</comments>
		<pubDate>Fri, 15 Jul 2011 13:08:21 +0000</pubDate>
		<dc:creator>todd anderson</dc:creator>
				<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Flex 4.5]]></category>

		<guid isPermaLink="false">http://custardbelly.com/blog/?p=457</guid>
		<description><![CDATA[*Maybe not necessarily hidden per se, but with the main focus on delivering Flex to mobile, there are a few things that have snuck into the Flex 4.5 SDK release that don&#8217;t get much coverage. I am not talking about Molehill, native JSON support, GC advice, etc. disclosed in this announcement &#8211; which are very [...]]]></description>
			<content:encoded><![CDATA[<p>*Maybe not necessarily <em>hidden</em> per se, but with the main focus on delivering <strong>Flex</strong> to mobile, there are a few things that have snuck into the <a href="http://opensource.adobe.com/wiki/display/flexsdk/Download+Flex+4.5" target="_blank">Flex 4.5 SDK</a> release that don&#8217;t get much coverage. I am not talking about <strong>Molehill</strong>, native <strong>JSON</strong> support, <strong>GC</strong> advice, etc. disclosed in <a href="http://www.bytearray.org/?p=3216" target="_blank">this announcement</a> &#8211; which are very exciting. I wanted to shed some light on some things I found kicking around in the new <strong>SDK</strong> that I have not heard very much about. Truthfully, they may have been a bi-product of getting the framework to be more performant on a mobile device &#8211; not sure &#8211; but they are things that I (and probably you) have created over and over for projects with varying degrees of functionality and <strong>API</strong> completeness as was deemed fit for the requirements at hand.</p>
<p>They are:</p>
<ol>
<li>s:Image</li>
<li>ContentCache</li>
<li>LinkedList</li>
</ol>
<p>read on to find out more about them&#8230;</p>
<h2>1. s:Image</h2>
<p>Finally, a <strong>Spark</strong> equivalent of <strong>mx:Image</strong>! And with it comes its own skin &#8211; <strong>ImageSkin</strong> &#8211; that allows the ability to show loading progress (with its own skin!). I can&#8217;t tell you how many times i have made these for client projects. Many &#8211; let&#8217;s keep it at that. However, the skin contract I would create for these custom &#8220;images-with-loading-indicator-components&#8221; (as I would call them) defined an <strong>mx:Image</strong> as the graphics container. The reason being a security issue with trying to manipulate bitmap data added to a <strong>BitmapImage</strong>.</p>
<p>Fortunately it looks like some updates to <strong>BitmapImage</strong> have been added as well in <a href="http://opensource.adobe.com/wiki/display/flexsdk/Download+Flex+4.5" target="_blank">Flex 4.5</a>, of which i am assuming clears up the security issues seeing as the skin contract for <strong>s:Image</strong> defines a <strong>BitmapImage</strong> as its graphic layer. Maybe I will dig into it later and come up with more info (or if someone reading knows, please tell), but what immediately pops out are the new <strong>load events and properties</strong> such as <em>trustedSource</em>, <em>contentLoader</em> and <em>bitmapData</em> (which returns a clone).</p>
<h3>Usage</h3>
<pre class="brush: xml; first-line: 1; title: ;">
&lt;s:Image source=&quot;http://upload.wikimedia.org/wikipedia/commons/archive/4/4e/20090913162821!Pleiades_large.jpg&quot;
                width=&quot;800&quot; height=&quot;600&quot;
                enableLoadingState=&quot;true&quot;
                /&gt;
</pre>
<p>Remember how i mentioned <em>contentLoader</em> as a new property for <strong>BitmapImage</strong> (and the decorating <strong>s:Image</strong>)? That is typed to an <strong>IContentLoader</strong> interface, of which <strong>ContentCache</strong> is an implementation.</p>
<h2>2. ContentCache</h2>
<p>Many 3rd party libraries have been written for this. I&#8217;ve created some in <strong>AS2</strong>, some in <strong>AS3</strong>. Basically just a lookup on file access either remote or embedded so as not to load or generate new content &#8211; some with load queues, some with instant request. And that is what <strong>ContentCache</strong> provides &#8211; a queueable, cacheable loader for files on a remote resource. Another cool feature is being able to assign a grouping for queued requests and priority in loading &#8211; (another property on <strong>s:Image</strong> and <strong>BitmapImage</strong> not addressed previously).</p>
<p>If we look at the <em>load</em>() signature on <strong>ContentCache</strong>:</p>
<pre class="brush: jscript; title: ;">
public function load(source:Object, contentLoaderGrouping:String=null):ContentRequest
</pre>
<p>we can see the grouping designation associated with the load request as the second argument. The first argument can be either a <strong>URLRequest</strong> object or a <strong>String</strong> (well <em>technically</em> you can supply anything there, but it will either be resolved to a <strong>URLRequest</strong> or <strong>String</strong> within the <em>load</em> function). We also see that <em>load</em>() returns an instance of <strong>ContentRequest</strong>. That can either be an active request in the queue or currently running or filled and considered <em>complete</em> from cache. </p>
<p>The <em>content</em> property on <strong>ContentRequest</strong> is typed as an Object and the docs suggest it can be anything. In the instance of the one returned from <strong>ContentCache</strong> it looks as though it is always typed to <strong>LoaderInfo</strong> (the target loader of the request). Pretty cool. So basically, you request <strong>ContentCache</strong> to load your image file, check for <em>complete</em> on the returned <strong>ContentRequest</strong>, if false, assign event handlers for complete. When using <strong>ContentCache</strong>, the <em>content</em> value on the <strong>ContentRequest</strong> (from what i see) will always be <strong>LoaderInfo</strong>. Obviously it is flexible enough to create your own <strong>IContentLoader</strong> implementation to return content of a different type.</p>
<h3>Usage</h3>
<pre class="brush: jscript; first-line: 1; title: ;">
public var cache:ContentCache;
public var requests:Vector.&lt;ContentRequest&gt;;

protected function requestImages():void
{
    cache = new ContentCache();
    cache.prioritize( &quot;walls&quot; );
    cache.enableCaching = true;
    cache.enableQueueing = true;

    requests = new Vector.&lt;ContentRequest&gt;();
    requests.push( cache.load( &quot;http://30.media.tumblr.com/tumblr_loc6v1EmWE1qzpsuoo1_500.jpg&quot;, &quot;superheros&quot; ) );
    requests.push( cache.load( &quot;http://26.media.tumblr.com/tumblr_locs8oFznL1qzpsuoo1_400.jpg&quot;, &quot;walls&quot; ) );
    requests.push( cache.load( &quot;http://25.media.tumblr.com/tumblr_loc2ysUcfw1qzpsuoo1_500.jpg&quot;, &quot;superheros&quot; ) )
    requests.push( cache.load( &quot;http://24.media.tumblr.com/tumblr_loarags4Du1qzpsuoo1_500.jpg&quot;, &quot;walls&quot; ) )

    var request:ContentRequest;
    var i:int = requests.length;
    while( --i &gt; -1 )
    {
        request = requests[i];
        if( request.complete )
        {
            requests.splice( i, 1 );
            addImage( (request.content as LoaderInfo).content as Bitmap );
        }
        else
        {
            addRequestHandlers( request );
        }
    }
}		

protected function addRequestHandlers( request:ContentRequest ):void
{
    request.addEventListener( Event.COMPLETE, handleRequestComplete );
}
protected function removeRequestHandlers( request:ContentRequest ):void
{
    request.removeEventListener( Event.COMPLETE, handleRequestComplete );
}

protected function handleRequestComplete( evt:Event ):void
{
    var request:ContentRequest = ( evt.target as ContentRequest );
    var index:int = requests.indexOf( request );
    requests.splice( index, 1 );
    removeRequestHandlers( request );

    var info:LoaderInfo = request.content as LoaderInfo;
    addImage( info.content as Bitmap );
}

protected function addImage( source:Bitmap ):void
{
    var img:BitmapImage = new BitmapImage();
    img.width = source.width;
    img.height = source.height;
    img.source = source;
    // imageHolder is just some container on the display list.
    imageHolder.addElement( img );
}
</pre>
<h3>The Good?</h3>
<p>Clean implementation. Remember that there is a <em>contentLoader</em> property on <strong>s:Image</strong> and <strong>BitmapImage</strong> now. You can use <strong>ContentLoader</strong> if it suits your needs, but you can also roll your own implementation of <strong>IContentLoader</strong>! I like.</p>
<h3>The Bad?</h3>
<p><em>Not necessarily bad implementations &#8211; we can certainly extend ContentLoader and make any modifications &#8211; these are more of things to consider when you are using it</em>:</p>
<p>There is no <em>add</em>() and <em>run</em>() on the API, or at least an <strong>autostart</strong> argument to <em>load</em>(). Invoking <em>load</em>() immediately starts loading. I may want to build a queue then kick it off. Plus it kind of kills the prioritize, because say your first two calls are #1) without priority association #2) with priority association. The first one is already in the loading process, so #2 does not take priority.</p>
<p>Even with prioritizing, do not rely on the order in which you call <em>load</em>() to be the order in which you will receive complete on the requests. This is mainly due to varying load times, priority, and cacheing. So if you are using <strong>ContentLoader</strong> as a queue loader, maintain the order outside of the <strong>ContentLoader</strong> and as requests come in as complete, fill that order accordingly. In essence, <strong>ContentLoader</strong> should be thought of &#8211; in my opinion &#8211; more of a cache of requests, rather than a queue loader per se. The <em>enableQueue</em> property does not pertain to &#8220;order in, order out&#8221; but rather &#8220;wait your turn&#8221;. The above example utilizes the priority API of <strong>ContentLoader</strong> to just show an example. If you run that a couple times, you will see what i mean about the order of the queue and priority being not what you would expect.</p>
<p>&#8230;</p>
<p>Now what caught my eye as I was checking out <strong>ContentCache</strong> is that is used linked lists, and more over that <strong>LinkedList</strong> was now available in the <strong>SDK</strong>! I&#8217;ll be it, in the <strong>mx.utils</strong> package (<em>why</em>?!) but still.</p>
<h2>3. LinkedList</h2>
<p>If you are unfamiliar with the concept of <a href="http://en.wikipedia.org/wiki/Linked_list" target="_blank">linked lists</a>, they are &#8211; in real simple terms &#8211; a great way to traverse a set of data using a node structure; unlike an array that stores data accessible from element index, a linked list really is more of an access point to nodes that have the knowledge of the next node and &#8211; depending on the type of linked list &#8211; at times, the previous node. </p>
<p>In the case of the <strong>LinkedList</strong> from the <a href="http://opensource.adobe.com/wiki/display/flexsdk/Download+Flex+4.5" target="_blank">Flex SDK</a> &#8211; which is a doubly linked list &#8211; each item in the list points to the previous and next item if existant. So you can imagine, if you want to traverse the list from the first element to the last, you just point the next node from the current node. Not only does each node hold a reference to the next and previous node, but also the data which you are storing. So basically when you add data to a linked list, you are requesting the data be wrapped in a node and hold reference to the previous and next node depending on where you insert it.</p>
<p>There have been some great implementations out there &#8211; such as ones found in <a href="http://lab.polygonal.de/as3ds/" target="_blank">polygonal&#8217;s data structures</a> &#8211; and i have built a couple in my day for clients with varying functionality based on requirements. </p>
<p>I should say that it is a great exercise to create your own linked list and I recommend that you should do so. The one included in the <strong>SDK</strong> is good, but in my opinion very limited (or maybe i should say &#8220;lightweight&#8221;) and its implementation is a little different than how I would have handled. But, implementation aside, there is a <strong>LinkedList</strong> in the <strong>SDK</strong> now. It&#8217;s bare bones. No iterator, no traversal <strong>API</strong> on the list itself, and you traverse by accessing the nodes directly through the list.</p>
<h3>Usage:</h3>
<pre class="brush: jscript; first-line: 1; title: ;">
var list:LinkedList = new LinkedList();
list.push( &quot;foo&quot; );
list.push( &quot;bar&quot; );
list.push( &quot;baz&quot; );

var node:LinkedListNode = list.head;
while( node.next )
{
    trace( &quot;Node value: &quot; + node.value );
    node = node.next;
}

// &lt;&lt;outputs&gt;&gt;
// Node value: foo
// Node value: bar
// Node value: baz
</pre>
<h3>The Good?</h3>
<p>If i need a simple linked list, i dont have to create a new one again&#8230; yay!</p>
<h3>The Bad?</h3>
<p><em>Again, not necessarily bad in implementation but things i may have done differently:</em></p>
<p>One thing i would prefer is that you don&#8217;t have access the <strong>LinkedListNode</strong> directly. I think that the node wrapper for your data should be hidden or only accessible from the linked list (or iterator). This means that access to the data is provided through another layer of <strong>API</strong> and when you call things like <em>head</em>(), <em>next</em>(), or <em>previous</em>() you would actually be returned the <strong>data</strong> you sent to store &#8211; not the <strong>node</strong>. And typically this would be resolved by exposing access to an <strong>iterator</strong> that provides an API to traverse the linked list. So, the linked list has an API on how to store the data (ie. <em>push</em>(), <em>insertAt</em>(), <em>remove</em>(), etc.) and the iterator has the traversal API (ie. <em>next</em>(), <em>previous</em>(), etc.). But that would just be my way of working with a linked list and I see nothing stopping me from adding that layer myself to this lightweight doubly linked list from the <strong>SDK</strong>.</p>
<p>Is it fast? I&#8217;ll leave that to <a href="http://jacksondunstan.com/articles/548" target="_blank">Jackson Dunstan</a> to find out&#8230; I am guessing no &#8211; or rather not as fast as it could be if it were part of the player globals like <strong>Array</strong> and <strong>Vector</strong>. And why oh why is it stuck in the <strong>mx</strong> package?!? I don&#8217;t mean to complain, but it seems like there is no reason to have <strong>LinkedList</strong> stuck in the <strong>Flex</strong> framework. There&#8217;s no binding. Its not even in <strong>MX</strong> collections. Whatever. Maybe it was just a quick implementation to use in request of icon images for speed on <strong>Flex mobile</strong>.</p>
<p>So in any event, I would say it is a great exercise to roll your own linked list so you have it for any <strong>ActionScript</strong>-only AND <strong>Flex</strong> projects. But you can also find some really useful implementations out there.</p>
<h2>Conclusion</h2>
<p>Nothing really to conclude. I just found these while digging around and became intrigued as they were fairly common things that i implemented over and over with varying functionality on projects based on requirements and now they are available in the Flex 4.5 SDK. If you have found some that you really like, let me know.</p>
]]></content:encoded>
			<wfw:commentRss>http://custardbelly.com/blog/2011/07/15/flex-4-5-hidden-additions/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Flash And The City: jQuery Mobile</title>
		<link>http://custardbelly.com/blog/2011/06/15/flash-and-the-city-jquery-mobile/</link>
		<comments>http://custardbelly.com/blog/2011/06/15/flash-and-the-city-jquery-mobile/#comments</comments>
		<pubDate>Wed, 15 Jun 2011 13:12:00 +0000</pubDate>
		<dc:creator>todd anderson</dc:creator>
				<category><![CDATA[Flash and the City]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jquery-mobile]]></category>

		<guid isPermaLink="false">http://custardbelly.com/blog/?p=450</guid>
		<description><![CDATA[Over the past weekend, I had the great pleasure to attend and present at Flash And The City in NYC. I want to thank Elad and Jose for putting on an excellent conference and giving me an opportunity to present. 
Download Source + Presentation
The talk was about the jQuery Mobile framework and was sort of [...]]]></description>
			<content:encoded><![CDATA[<p>Over the past weekend, I had the great pleasure to attend and present at <a href="http://fatc.co/" target="_blank">Flash And The City</a> in NYC. I want to thank <a href="https://twitter.com/#!/eladelrom" target="_blank">Elad</a> and <a href="https://twitter.com/#!/joseeight" target="_blank">Jose</a> for putting on an excellent conference and giving me an opportunity to present. </p>
<p><a href="http://www.custardbelly.com/presentations/FATC/jqm/jQM_FATC.zip">Download Source + Presentation</a></p>
<p>The talk was about the <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a> framework and was sort of a nuts and bolts overview of what the framework has to offer and its foundation on the principal of <a href="http://www.alistapart.com/articles/understandingprogressiveenhancement" target="_blank">Progressive Enhancement</a>. Thanks to all who made it out. I really appreciate it and hopefully it was worth taking you away from the beautiful city for a little bit.</p>
<div style="width:425px" id="__ss_8302294"><strong style="display:block;margin:12px 0 4px"><a href="http://www.slideshare.net/todd_anderson/jquery-mobile-progressive-enhancement-with-html5-8302294" title="jQuery Mobile: Progressive Enhancement with HTML5">jQuery Mobile: Progressive Enhancement with HTML5</a></strong><object id="__sse8302294" width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=fatcjqm-110614051649-phpapp01&#038;stripped_title=jquery-mobile-progressive-enhancement-with-html5-8302294&#038;userName=todd_anderson" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed name="__sse8302294" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=fatcjqm-110614051649-phpapp01&#038;stripped_title=jquery-mobile-progressive-enhancement-with-html5-8302294&#038;userName=todd_anderson" 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/todd_anderson">Todd Anderson</a>.</div>
</div>
<p>You can also check out a loose transcript of what i *may* have said here: <a href="http://www.custardbelly.com/presentations/FATC/jqm/FATC_jQM_Transcript.pdf" target="_blank">jQuery Mobile: Progressive Enhancement with HTML5 [FATC 2011] transcript</a>. [<strong>Warning</strong> - its a PDF] </p>
<p>There were more slides than the time allotted and I didn&#8217;t want to keep those who were nice enough to attend from exploring the city by watching me ramble on over my time limit. So i can&#8217;t guarantee that the transcript was true to the presentation; it was more of a rough draft of my thoughts on the slides.</p>
<p>All the demo source code and a PDF of the slide-deck can be downloaded here as well:<br />
<a href="http://www.custardbelly.com/presentations/FATC/jqm/jQM_FATC.zip">Download Source + Presentation</a></p>
<p>Thanks again to everyone who came out and to <a href="https://twitter.com/#!/eladelrom" target="_blank">Elad</a> and <a href="https://twitter.com/#!/joseeight" target="_blank">Jose</a> for putting on another great <a href="http://fatc.co/" target="_blank">Flash And The City</a> conference!</p>
<p>Link dump of what i may have mentioned and what is in the slides:</p>
<p><a href="http://fatc.co/">Flash And The City</a><br />
<a href="http://jquerymobile.com">jQuery Mobile</a><br />
<a href="http://jquerymobile.com/gbs/">jQuery Mobile A-Grade browser support</a><br />
<a href="http://www.alistapart.com/articles/understandingprogressiveenhancement">Progressive Enhancement</a><br />
<a href="http://selleckwaterfallsandwich.tumblr.com/">Selleck Waterfall Sandwich</a><br />
<a href="http://jeromeetienne.github.com/jquery-mobile-960/">jQuery Mobile: 960</a><br />
<a href="http://www.famfamfam.com/lab/icons/silk/">FamFamFam icons</a><br />
<a href="http://jqueryui.com/themeroller/">jQuery UI Theme Roller</a><br />
<a href="http://www.w3.org/WAI/intro/aria.php">WAI-ARIA</a><br />
<a href="http://dev.opera.com/articles/view/introduction-to-wai-aria/">Introduction to WAI ARIA by Gez Lemon</a><br />
<a href="http://dayofjs.com/videos/22152945/jquery-mobile_scott-jehl">Presentation by Scott Jehl of the Filament Group (specifically the Screen Reader demo)</a><br />
<a href="http://labjs.com">LabJS</a><br />
<a href="http://yepnopejs.com/">yepnope</a><br />
<a href="http://www.modernizr.com/">Modernizr</a><br />
<a href="http://developer.apple.com/library/safari/#documentation/appleapplications/reference/ SafariHTMLRef/Articles/MetaTags.html">Web-App Meta</a><br />
<a href="documentation/appleapplications/reference/ safariwebcontent/configuringwebapplications/configuringwebapplications.html<br />
http://developer.apple.com/library/safari/#">WebClips</a><br />
<a href="http://diveintohtml5.org/offline.html">HTML5 cache.manifest</a><br />
<a href="http://www.phonegap.com">PhoneGap</a><br />
<a href="http://labs.adobe.com/technologies/flashplatformruntimes/">Adobe AIR</a><br />
<a href="http://voisen.org/blog/2010/10/making-the-most-of-stagewebview/">Making the most of StageWebView by Sean Voisen</a><br />
<a href="http://www.nimblekit.com/">NimbleKit</a><br />
<a href="http://quickconnectfamily.org/">QuickConnectFamily</a><br />
<a href="http://www.appcelerator.com/">Titanium</a><br />
<a href="http://rhomobile.com/products/rhodes/">Rhodes</a><br />
<a href="http://infrared5.com">Infrared5</a><br />
<a href="https://twitter.com/#!/bustardcelly">me on twitter</a></p>
]]></content:encoded>
			<wfw:commentRss>http://custardbelly.com/blog/2011/06/15/flash-and-the-city-jquery-mobile/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery Mobile + CouchDB: Part 7.2 – Authorization and Validation</title>
		<link>http://custardbelly.com/blog/2011/03/04/jquery-mobile-couchdb-part-7-2-%e2%80%93-authorization-and-validation/</link>
		<comments>http://custardbelly.com/blog/2011/03/04/jquery-mobile-couchdb-part-7-2-%e2%80%93-authorization-and-validation/#comments</comments>
		<pubDate>Fri, 04 Mar 2011 16:42:08 +0000</pubDate>
		<dc:creator>todd anderson</dc:creator>
				<category><![CDATA[CouchDB]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jquery-mobile]]></category>

		<guid isPermaLink="false">http://custardbelly.com/blog/?p=394</guid>
		<description><![CDATA[In my previous post, I covered authorization and validation on the CouchDB side. We set up an administrator, created a user or two and established a user-role for our albums database that will be used in validation on document operations based on the user context of a session. We got to write some code &#8211; [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://custardbelly.com/blog/?p=360" target="_blank">previous post</a>, I covered authorization and validation on the <a href="http://couchdb.apache.org/" target="_blank">CouchDB</a> side. We set up an administrator, created a user or two and established a <strong>user-role</strong> for our <strong>albums</strong> database that will be used in validation on document operations based on the user context of a session. We got to write some code &#8211; our <strong>validate_doc_update</strong> &#8211; but mainly it was all clicking around and filling in fields in <a href="http://127.0.0.1:5984/_utils/" target="_blank">Futon</a>. Necessary stuff, mind you&#8230; but let&#8217;s get back to code. More importantly, let&#8217;s get back to our <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a> application. We didn&#8217;t even touch it in the last mini-series in a series.</p>
<p>In this article I am going to address showing a <strong>Log In/Sign Up</strong> dialog in our <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a> application. Instead of forcing a user to log in upon first landing on our application (as we saw when setting up <strong>Security</strong> on our database in the past article), we are going to present the dialog when a user tries to perform an operation that requires session and user validation. The way we have set up the <strong>albums</strong> database in <a href="http://couchdb.apache.org/" target="_blank">CouchDB</a> is that everyone can view all the <strong>album</strong> documents, but only users of the <strong>albums</strong> database (those assigned with a <strong>user-role</strong> of &#8220;<em>albums-user</em>&#8220;) are allowed to add new <strong>album</strong> documents and only those associated users of a document are allowed to edit and delete their <strong>album</strong> document. So, from a client-side perspective, the dialog will be shown on <strong>Add</strong>, <strong>Edit</strong> and <strong>Delete</strong> if a previous session for the user has not been established.</p>
<p>Actually, it is probably a little misleading to say we will be doing all this in <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a>. I am actually going to incorporate <a href="http://jquery.com/" target="_blank">jQuery</a> concepts into our <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a> application. We are going to present the dialog as a <a href="http://jquery.com/" target="_blank">jQuery</a> <strong>widget</strong> and manage the communication through a <a href="http://jquery.com/" target="_blank">jQuery</a> <strong>plugin</strong> for our application. So as far as the <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a> framework is concerned, we won&#8217;t be learning anything new per se &#8211; we&#8217;ll be learning how to incorporate <a href="http://jquery.com/" target="_blank">jQuery</a> <strong>widgets</strong> and <strong>plugins</strong> into our application. In previous articles, the main bulk of <a href="http://jquery.com/" target="_blank:>jQuery</a> we have employed has been using accessors and modifiers for elements/events within our <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a> application. We have also gotten familiar with the <em>jquery.couch</em> plugin that comes with <a href="http://couchdb.apache.org/" target="_blank">CouchDB</a> and handles most (if not all) the communication points we need for our application. So working with the <a href="http://jquery.com/" target="_blank">jQuery</a> library is not all that unfamiliar.</p>
<p>Right. Didn&#8217;t i say there will be more coding in this article? What am i doing yammering on? Its time to put your <a href="http://jquery.com/" target="_blank">jQuery</a> hats on, because its about to get a whole lot more fun*!</p>
<p><em>*guarantees not included.</em></p>
<h2>Template</h2>
<p>We are going to create a <strong>login dialog</strong> pretty much as your standard form with the option to either &#8220;<em>log in</em>&#8221; or &#8220;<em>sign up</em>&#8221; (if i ever don&#8217;t use the space in those and it bothers you, i apologize. its become a little habit). In our planning, we currently want the dialog to appear in at least 3 places based on an operation that requires session and user validation &#8211; <strong>Add</strong>, <strong>Edit</strong> and <strong>Delete</strong>. Down the road, there could be more. We could add a login button to some or every page to allow to login at any time within the application. We&#8217;ll stick to the 3 operations for now, but in knowing that the same visual piece will be used in multiple places throughout the application, it makes for a good case to use a template for the UI of our login dialog.</p>
<p>We learned about templates on the <a href="http://couchdb.apache.org/" target="_blank">CouchDB</a> side previously &#8211; using <a href="https://github.com/janl/mustache.js/" target="_blank">Mustache</a> and <strong>Partials</strong> to create our views. Same concept. We want to be able to declare some mark-up in one place that will be rendered in the <strong>DOM</strong> upon request from anywhere in the application. To do that, we&#8217;ll use the <a href="http://github.com/jquery/jquery-tmpl" target="_blank">jquery.tmpl</a> plugin available at: <a href="http://github.com/jquery/jquery-tmpl" target="_blank">http://github.com/jquery/jquery-tmpl</a>. Why jquery.tmpl? It is simple to use and &#8211; though still in beta &#8211; is considered an <a href="http://www.borismoore.com/2010/10/jquery-templates-is-now-official-jquery.html" target="_blank">official jQuery plugin</a>, so documentation can be found on the <a href="http://jquery.com/" target="_blank">jQuery</a> site at: <a href="http://api.jquery.com/jquery.tmpl/" target="_blank">http://api.jquery.com/jquery.tmpl/</a>. In any event, make sure to download the jquery.tmpl plugin from <a href="http://github.com/jquery/jquery-tmpl" target="_blank">http://github.com/jquery/jquery-tmpl</a> as we are going to use it for our login dialog.</p>
<p>With <em>jquery.tmpl</em> downloaded and added to the <em>/vendor/couchapp/_attachments/</em> folder of our <strong>albums</strong> <a href="http://couchapp.org/page/index" target="_blank">coucapp</a> directory (in following the examples within this series, for me that directory is <em>/Documents/workspace/custardbelly/couchdb/albums</em>), open up the <em>loader.js</em> file from that same directory and save the following modification to include the <em>jquery.tmpl</em>:</p>
<p><em>/vendor/couchapp/_attachments/loader.js</em></p>
<pre class="brush: jscript; first-line: 1; highlight: [17]; title: ;">
function couchapp_load(scripts) {
  for (var i=0; i &lt; scripts.length; i++) {
    document.write('&lt;script src=&quot;'+scripts[i]+'&quot;&gt;&lt;\/script&gt;')
  };
};

couchapp_load([
  &quot;/_utils/script/sha1.js&quot;,
  &quot;/_utils/script/json2.js&quot;,
  &quot;vendor/couchapp/jquery-1.4.4.js&quot;,
  &quot;/_utils/script/jquery.couch.js&quot;,
  &quot;vendor/couchapp/jquery.couch.app.js&quot;,
  &quot;vendor/couchapp/jquery.couch.app.util.js&quot;,
  &quot;vendor/couchapp/jquery.mustache.js&quot;,
  &quot;vendor/couchapp/jquery.evently.js&quot;,
  &quot;vendor/couchapp/jquery.mobile-1.0a2.js&quot;,
  &quot;vendor/couchapp/jquery.tmpl.js&quot;
]);
</pre>
<p>Pretty straight forward; just adding the <em>jquery.tmpl</em> <strong>plugin</strong> to be loaded into the <strong>DOM</strong>. Now we need to declare the mark-up for our <strong>login dialog</strong>. We&#8217;ll just add it to our main page and its usage will be revealed later. For now, open up the <em>/_attachments/index.html</em> file and save the following script tag and content between the previously declared script tags for the <em>loader.js</em> and our application script:</p>
<pre class="brush: xml; first-line: 52; highlight: [53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73]; title: ;">
&lt;script src=&quot;vendor/couchapp/loader.js&quot;&gt;&lt;/script&gt;
&lt;script id=&quot;loginSignupDialog&quot; type=&quot;text/x-jquery-tmpl&quot;&gt;
    &lt;div role=&quot;dialog&quot; data-backbtn=&quot;false&quot; class=&quot;ui-dialog ui-body-a&quot;&gt;
      &lt;div class=&quot;ui-header ui-bar-a ui-corner-top ui-overlay-shadow&quot;&gt;
	&lt;h1 class=&quot;ui-title&quot;&gt;&lt;/h1&gt;
	&lt;a id=&quot;dialogCloseButton&quot; href=&quot;#&quot; data-icon=&quot;delete&quot; data-iconpos=&quot;notext&quot; style=&quot;left: 15px; top: .4em; position: absolute;&quot; /&gt;
      &lt;/div&gt;
      &lt;div data-role=&quot;content&quot; class=&quot;ui-body-c ui-corner-bottom ui-overlay-shadow&quot;&gt;
        &lt;p&gt;You need to be logged in to do that!&lt;/p&gt;
        &lt;form action=&quot;#&quot; method=&quot;post&quot;&gt;
          &lt;label for=&quot;username&quot;&gt;Username:&lt;/label&gt;
          &lt;input type=&quot;text&quot; name=&quot;username&quot; id=&quot;username&quot; value=&quot;&quot;  /&gt;
          &lt;label for=&quot;password&quot;&gt;Password:&lt;/label&gt;
          &lt;input type=&quot;password&quot; name=&quot;password&quot; id=&quot;password&quot; value=&quot;&quot; /&gt;
          &lt;a id=&quot;submitButton&quot; href=&quot;#&quot; type=&quot;submit&quot; data-role=&quot;button&quot; data-theme=&quot;b&quot;&gt;Submit&lt;/a&gt;
          &lt;hr/&gt;
          &lt;a id=&quot;optionLinkButton&quot; href=&quot;#&quot; /&gt;
        &lt;/form&gt;
      &lt;/div&gt;
      &lt;div data-role=&quot;footer&quot; /&gt;
    &lt;/div&gt;
&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; charset=&quot;utf-8&quot;&gt;
     $db = $.couch.db(&quot;albums&quot;);
</pre>
<p>The <strong>loginSignupDialog</strong> template looks pretty familiar if you have been following along in this series. It is just a hacked up <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a> page dialog with a form &#8211; looks pretty much what our <em>albumdelete.html</em> <strong>template</strong> we created before but with a form in it. You may notice that the header and <strong>optionLinkButton</strong> have no textual content. That will be updated based on the state of the dialog (login or signup). We&#8217;ll get to that later. What is important is to know that this template declaration can be rendered using the following:</p>
<pre class="brush: jscript; title: ;">
$(&quot;#loginSignupDialog&quot;).tmpl()
</pre>
<p>Once it has been rendered it can be added to the <strong>DOM</strong> as you normally would with <a href="http://jquery.com/" target="_blank">jQuery</a> (eg, <em>appendTo</em>()), but since we are developing in the context of a <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a> application, we will treating it as a page in the application. Things to remember and will act upon later.</p>
<p>Also important to note is the type attribute of the <strong>template</strong> declaration &#8211; <em>text/x-jquery-tmpl</em>. That is so the <strong>HTML</strong> parser knows to treat that markup as a string and not try to parse and add to the <strong>DOM</strong>. Without that type, you likely will get a parse error when viewing your application in a browser. The plugin does not search for the explicit type value of <em>text/x-jquery-tmpl</em> in order to due its rendering, it just needs to have some denotation for the browser engine to recognize not to render the content to the <strong>DOM</strong> &#8211; <em>text/x-jquery-tmpl</em> is just easier to recognize what is being reserved as a <a href="http://jquery.com/" target="_blank">jQuery</a> template by human readers.</p>
<h2>Organization and Re-use</h2>
<p>Up to this point in the series, if you have been following along, the extent of our working with <a href="http://jquery.com/" target="_blank">jQuery</a> has been in accessing and modifying the <strong>DOM</strong>. We&#8217;ve used the <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a> API mainly to listen for events and change pages. The extent of working with the <a href="http://jquery.com/" target="_blank">jQuery Mobile</a> framework has been more under the hood &#8211; which i believe is the intent &#8211; though we have employed some hacks to get things to work as we would like. So, the <strong>JavaScript</strong> we have done up until this point has been to manipulate the <strong>DOM</strong> associated with a particular view &#8211; we created our <strong>Partials</strong> as quasi-view controllers and we have some script related to the <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a> pages we have defined in <em>index.html</em>.</p>
<p>That&#8217;s fine. I might do some things a little different if this was going to get my seal of approval, but we were having fun. I&#8217;m gonna get a little more organized now, however, and use some great functionality and <strong>API</strong> available to us just by loading <a href="http://jquery.com/">jQuery</a> and <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a> that we have been foolishly ignoring. Not really ignoring&#8230; we just never had a really strong use case to address it until now.</p>
<p>We are going to employ two architectural concepts of jQuery in order to present our login dialog and authenticate session with our <a href="http://couchdb.apache.org/" target="_blank">CouchDB</a> instance: <strong>widgets</strong> and <strong>plugins</strong>.</p>
<p>Before we dive into some code, perhaps I should clarify how I interpret each concept as really they can be somewhat interchangeable and used in the same fashion. For instance they both can target an element like so:</p>
<pre class="brush: jscript; title: ;">
$(&quot;#myElement&quot;).something();
</pre>
<p>It is typically the <em>something</em>() invocation, for me, that sets them apart (aside from the code behind the <em>something</em>()). If it is a directive to manipulate the element or its ancestry in the <strong>DOM</strong>, then it is a plugin. If it is a call to decorate the element in such a way that it looks and behaves in a manner usually not associated with that element, then i consider it a <strong>widget</strong> <em>(in fact, as we will discuss later, there is more to this in terms of a factory/builder plugin for widgets)</em>. Say for instance: <strong>$(&#8221;#myElement&#8221;)</strong>.<em>slider</em>() would manipulate the contents of <strong>#myElement</strong> to behave like a slider control.</p>
<p>And then of course, plugins can declare a global access variable and define an <strong>API</strong>, as we have seen with <strong>$.mobile</strong> (<em>jquery-mobile-1.0a2.js</em>) and <strong>$.couch</strong> (<em>jquery.couch.js</em>), which takes the <strong>plugin</strong> concept from being more of a &#8220;utility&#8221; method on element(s) to that of a library.</p>
<p>Of course, I could be totally off-base in how i interpret these concepts and am open to discussion. If you have different interpretations or more insight please leave a comment.</p>
<h2>Widget</h2>
<p>Truthfully, a <strong>widget</strong> is more tied with the <a href="http://jqueryui.com/" target="_blank">jQuery UI</a> library. Included in the development-bundle source for <a href="http://jqueryui.com/" target="_blank">jQuery UI</a> is a <em>jquery.ui.widget</em> script that defines the <strong>widget</strong> factory/builder and the defined UI <strong>widget</strong> elements with the <strong>jquery.ui.*</strong> namespaced file name. We are not going to load the <a href="http://jqueryui.com/" target="_blank:>jQuery UI</a> library as well, since <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a> basically contains that script from <em>jquery.ui.widget</em> and extends it to <strong>mobile.widget</strong> to preform some string manipulation on the data attribute. In fact, most of the controls (and even page!) that are &#8220;mobilized&#8221; are widgets.</p>
<p>So we have <strong>$.widget</strong> at our disposal (thanks to <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a>). We&#8217;ll use the <strong>$.widget</strong> factory to create a <strong>login dialog</strong> widget to provide functional logic to our <strong>login template</strong> create previously in this article. In this sense, you can think of the <strong>login dialog widget</strong>, itself, as a sort of presenter. We can go about mucking around with the layout and such of our template and wire up our widget to respond to events from elements in our view.</p>
<p>Before we dive right in to some code, I wanted to touch on some finer points so when we take a look at how our <strong>login dialog widget</strong> is created we might have a clearer understanding of its construction. <strong>$.widget</strong> is considered a factory method to create custom widgets and is an extension of <strong>$.Widget</strong> (capital W). <strong>$.Widget</strong> itself acts as sort of a builder. Upon widget-ization of an element, <em>_init</em>() and <em>_create</em>() hook methods are invoked and available for override in our custom <strong>widget</strong>. There are also some methods for options, enablement, and for triggering events (<em>_trigger</em>()) to name a few. But most importantly, there is a <em>destroy</em>() method. To squash any memory leaks, we must tidy up our mess. </p>
<p>So, to break it down, <strong>$.Widget</strong> provides a lifecycle method template and is the builder of our <strong>widget</strong>. <strong>$.widget</strong> is a factory method for creating custom widgets and allows us to widget-ize elements based on the name of our widget. <em>What the hell does that mean?</em> If we create a widget using the <strong>$.widget</strong> factory and provide it a name of &#8220;<em>albums.loginDialog</em>&#8220;, we can widget-ize our template as such:</p>
<pre class="brush: jscript; title: ;">
$(&quot;#loginSignupDialog&quot;).tmpl().loginDialog()
</pre>
<p>In fact, that is essentially what we are going to do&#8230; but we first lets cover how we&#8217;re going to do it. For some extra reading, this is a great article form <a href="http://jqueryui.com/" target="_blank">jQuery UI</a> explaining the widget factory: <a href="http://jqueryui.com/docs/Developer_Guide" target="_blank">http://jqueryui.com/docs/Developer_Guide</a>. There is also this excellent write up i found by <a href="http://www.erichynds.com" target="_blank">Eric Hynds</a>: <a href="http://www.erichynds.com/jquery/tips-for-developing-jquery-ui-widgets/" target="_blank">http://www.erichynds.com/jquery/tips-for-developing-jquery-ui-widgets/</a>.</p>
<p>Less talk. More code. Open up your favorite editor and save the following snippet as <em>jquery.albums.loginDialog.js</em> in the <em>/_attachments/script</em> directory of the <strong>albums</strong> <a href="http://couchapp.org/page/index" target="_blank">couchapp</a> (for me that directory is <em>/Documents/workspace/custardbelly/couchdb/albums</em>):</p>
<p><em>/_attachments/script/jquery.albums.loginDialog.js</em></p>
<pre class="brush: jscript; first-line: 1; title: ;">
(function( $ ) {

  $.widget( &quot;albums.loginDialog&quot;, {

    options: {
      state: 0, // 0 - log in state. 1 - sign up state.
      loginText: &quot;Log In&quot;,
      signUpText: &quot;Sign Up&quot;
    },

    _create: function() {
      var ops = this.options;
      var $element = this.element;

      // Current page reference.
      var currentPage = $.mobile.activePage;
      var pageLink = currentPage.attr( &quot;id&quot; );
      // It is an internal page link.
      if( pageLink.indexOf( &quot;.html&quot; ) == -1 ) pageLink = &quot;#&quot; + pageLink;
      var closeButton = $element.find( &quot;div[class*='ui-header'] a#dialogCloseButton&quot; )
                                .attr( &quot;href&quot;, pageLink );
      // Hold reference in custom data expando.
      $element.data(&quot;previous&quot;, pageLink );

      // Wrap the content in a dialog page.
      var wrapper = this._wrapDialog( $element );
      // Wire interactions.
      this._wire();
      this._changeState( ops.state );
      // For some reason, i have to add it to the DOM in order to changePage() to it.
      $(&quot;body[class*=\&quot;ui-mobile-viewport\&quot;]&quot;).append(wrapper);
      $.mobile.changePage( [currentPage, wrapper], &quot;pop&quot;, false );
    },

    _setOption: function( key, value ) {
      this._changeState( ( key == &quot;state&quot; ) ? value : this.options.state );
      jQuery.Widget.prototype._setOption.apply( this, arguments );
    },

    _wrapDialog: function( dialogElement ) {
      // Page wrapper usually created on external page.
      var dialogPage = $(&quot;&lt;div data-role=\&quot;page\&quot;&gt;&quot;);
      dialogPage.append( dialogElement );
      dialogPage.page();

      dialogPage.bind( &quot;pagebeforeshow&quot;, function() {
          dialogPage.unbind( &quot;pagebeforeshow&quot; );
          var h = parseFloat(dialogPage.innerHeight());
          h -= ( parseFloat(dialogElement.css(&quot;border-top-width&quot;)) + parseFloat(dialogElement.css(&quot;border-bottom-width&quot;)) );
          // define the height based on innerHeight of wrapping parent page and the border styles applied to a dialog.
          dialogElement.css( &quot;height&quot;, h + &quot;px&quot; );
      });
      dialogPage.bind( &quot;pagehide&quot;, function() {
          dialogPage.unbind( &quot;pagehide&quot; );
          dialogPage.empty();
          dialogPage.remove();
      });
      return dialogPage;
    },

    _changeState: function( state ) {
      var mainText = ( state == 0 ) ? this.options.loginText : this.options.signUpText;
      var optionText = ( state == 0 ) ? this.options.signUpText : this.options.loginText;
      var $element = this.element;
      var header = $element.find( &quot;div[class*='ui-header']&quot; );
      var page = $element.find( &quot;div[data-role='content']&quot; );
      var title = header.find( &quot;[class*='ui-title']&quot; );
      var optionLinkButton =  page.find( &quot;#optionLinkButton&quot; );
      var submitButton = page.find( &quot;a[aria-label='submit']&quot; );
      title.html( mainText );
      optionLinkButton.html( optionText + &quot;?&quot; );
      submitButton.html( mainText );
      submitButton.buttonMarkup();
    },

    _wire: function() {
      var ref = this;
      var $element = ref.element;
      var ops = ref.options;
      var page = $element.find(&quot;div[data-role='content']&quot;);
      var optionLinkButton = page.find( &quot;#optionLinkButton&quot; );

      optionLinkButton.bind( &quot;click&quot;, function(event) {
        event.preventDefault();
        // toggle state.
        ref._setOption( &quot;state&quot;, ( ops.state == 1 ) ? 0 : 1 );
        return false;
      });

      $element.bind( &quot;submit&quot;, function(event) {
        event.preventDefault();
        var username = $element.find( &quot;input#username&quot; ).val();
        var password = $element.find( &quot;input#password&quot; ).val();
        var uievent = ( ops.state == 0 ) ? &quot;login&quot; : &quot;signup&quot;;
        var ui = {name:username, password:password};
        ref._trigger( uievent, {type:uievent}, ui );
        return false;
      });
    },

    _unwire: function() {
      var $element = this.element;
      var page = $element.find( &quot;div[data-role='content']&quot; );
      var optionLinkButton =  page.find( &quot;#optionLinkButton&quot; );
      optionLinkButton.unbind( &quot;click&quot; );
      $element.unbind( &quot;submit&quot; );
    },

    close: function() {
      var $element = this.element;
      this._trigger( &quot;close&quot;, {type:&quot;close&quot;} );
      $.mobile.changePage( $element.data(&quot;previous&quot;), undefined, false );
    },

    destroy: function() {
      this._unwire();
      // jQuery Mobile keeps adding a Submit button substitue to the template upon show,
      // Lets remove it here.
      var $element = this.element;
      var page = $element.find( &quot;div[data-role='content']&quot; );
      var submitButton = page.find( &quot;a[aria-label='submit']&quot; );
      submitButton.remove();
      // super destroy.
      jQuery.Widget.prototype.destroy.call( this );
      this.element = null;
    }

  });

})(jQuery)
</pre>
<p>You wanted code? You got it <img src='http://darko.liquidweb.com/~custardb/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  I am not going to go into explaining the under-workings of <strong>$.widget</strong> or <strong>$.Widget</strong> but more the work we have here that relates to <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a> and our application. Again, if you are curious, <a href="http://jqueryui.com/" target="_blank">jQuery UI</a> has some great documentation at <a href="http://jqueryui.com/docs/Developer_Guide" target="_blank">http://jqueryui.com/docs/Developer_Guide</a> and you can also look at the <strong>JavaScript</strong> source for <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a>. That is chock full of widgets. And then there is this awesome write up by <a href="http://www.erichynds.com" target="_blank">Eric Hynds</a>: <a href="http://www.erichynds.com/jquery/tips-for-developing-jquery-ui-widgets/" target="_blank">http://www.erichynds.com/jquery/tips-for-developing-jquery-ui-widgets/</a>.</p>
<p>Now, let&#8217;s step through it&#8230; If you are being introduced to <a href="http://jquery.com/" target="_blank">jQuery</a> by this article series: <strong>a)</strong> i hope i have not mislead you in my explanations and <strong>b)</strong> this might be the first time you have seen this anonymous function declaration:</p>
<pre class="brush: jscript; first-line: 1; title: ;">
(function( $ ) {
...
})(jQuery)
</pre>
<p>There is more going on here (conflict resolution) than i will explain, but in essence this is a self-executing method that has a reference to <a href="http://jquery.com/" target="_blank">jQuery</a>. Basically, upon load any code within this anonymous function will be run and have access to <a href="http://jquery.com/" target="_blank">jQuery</a> using the <strong>$</strong> token; once <em>jquery.albums.loginDialog.js</em> is loaded, we invoke the <strong>$.widget</strong> factory method to create a <strong>widget</strong> accessible via <em>loginDialog</em>() on an element reference:</p>
<p><em>/_attachments/script/jquery.albums.loginDialog.js</em></p>
<pre class="brush: jscript; first-line: 3; title: ;">
$.widget( &quot;albums.loginDialog&quot;, {
...
} );
</pre>
<p>The second argument to <strong>$.widget</strong> &#8211; the whole big object &#8211; is basically the meat of our <strong>widget</strong>; its got some declared default options, overidden inherited methods and some other private and public methods to make our <strong>loginDialog</strong> work. Our options are just some default values to set the initial state (either to <em>login</em> or <em>signup</em>) and the textual content associated with the state. Our <strong>login dialog</strong> isn&#8217;t going to be very pretty or contain much content other than a form and a way to switch between <em>login</em> and <em>signup</em>.</p>
<p><em>/_attachments/script/jquery.albums.loginDialog.js</em></p>
<pre class="brush: jscript; first-line: 5; title: ;">
options: {
  state: 0, // 0 - log in state. 1 - sign up state.
  loginText: &quot;Log In&quot;,
  signUpText: &quot;Sign Up&quot;
},
</pre>
<p>When it enters <em>_create</em>() (inheritance call from <strong>$.Widget</strong>), is when we do some real magic:</p>
<p><em>/_attachments/script/jquery.albums.loginDialog.js</em></p>
<pre class="brush: jscript; first-line: 13; title: ;">
var $element = this.element;

// Current page reference.
var currentPage = $.mobile.activePage;
var pageLink = currentPage.attr( &quot;id&quot; );
// It is an internal page link.
if( pageLink.indexOf( &quot;.html&quot; ) == -1 ) pageLink = &quot;#&quot; + pageLink;
var closeButton = $element.find( &quot;div[class*='ui-header'] a#dialogCloseButton&quot; )
                          .attr( &quot;href&quot;, pageLink );
// Hold reference in custom data expando.
$element.data(&quot;previous&quot;, pageLink );
</pre>
<p>The target element (the one widget-ized by calling <strong>$(&#8221;#myElement&#8221;)</strong>.<em>loginDialog</em>()) is accessed using the this keyword and is available through the life of the <strong>widget</strong>. In order to get a reference to the current page prior to opening the <strong>loginDialog</strong>, we access the id value of <strong>$.mobile</strong>.<em>activePage</em> and determine if it is an external or internal page. We then pass that as the href value for the close button on the <strong>loginDialog</strong> and add a <strong>data-previous</strong> attribute to the target element. </p>
<p>After the previous page has been determined to return to after login or signup, we then wrap the <strong>dialog template</strong> element in a page <strong>div</strong> listen for events, change the state to the default defined in options and change the page to the <strong>loginDialog</strong>:</p>
<p><em>/_attachments/script/jquery.albums.loginDialog.js</em></p>
<pre class="brush: jscript; first-line: 25; title: ;">
// Wrap the content in a dialog page.
var wrapper = this._wrapDialog( $element );
// Wire interactions.
this._wire();
this._changeState( ops.state );
// For some reason, i have to add it to the DOM in order to changePage() to it.
$(&quot;body[class*=\&quot;ui-mobile-viewport\&quot;]&quot;).append(wrapper);
$.mobile.changePage( [currentPage, wrapper], &quot;pop&quot;, false );
</pre>
<p>You see that funky append before <strong>$.mobile</strong>.<em>changePage</em>()?</p>
<p><em>/_attachments/script/jquery.albums.loginDialog.js</em></p>
<pre class="brush: jscript; first-line: 31; title: ;">
$(&quot;body[class*=\&quot;ui-mobile-viewport\&quot;]&quot;).append(wrapper);
</pre>
<p>The comment above that line explains it, but for some reason i couldn&#8217;t just switch to this dynamically created page. Instead i had to add it quickly at the end of the body (accessed by the <em>ui-mobile-viewport</em> class) and then was able to switch from the previous page to show a <strong>loginDialog</strong>. No big deal, just something to look out for. </p>
<p>Most of what is in <em>jquery.albums.loginDialog</em>, if you have been following along, may be pretty familiar to you. We do the same sizing on <em>pagebeforeshow</em> and emptying on <em>pagehide</em>, and change values based on state using <a href="http://jquery.com/" target="_blank">jQuery</a>. Your basic fanfare. I just wanted to touch on two more methods in <em>jquery.albums.loginDialog</em>: <em>close</em> and <em>destroy</em>:</p>
<p><em>/_attachments/script/jquery.albums.loginDialog.js</em></p>
<pre class="brush: jscript; first-line: 109; title: ;">
close: function() {
var $element = this.element;
this._trigger( &quot;close&quot;, {type:&quot;close&quot;} );
$.mobile.changePage( $element.data(&quot;previous&quot;), undefined, false );
},

destroy: function() {
  this._unwire();
  // jQuery Mobile keeps adding a Submit button substitue to the template upon show,
  // Lets remove it here.
  var $element = this.element;
  var page = $element.find( &quot;div[data-role='content']&quot; );
  var submitButton = page.find( &quot;a[aria-label='submit']&quot; );
  submitButton.remove();
  // super destroy.
  jQuery.Widget.prototype.destroy.call( this );
  this.element = null;
}
</pre>
<p>The <em>close</em>() method we have exposed and is not part of <strong>$.Widget</strong>. That just allows access to anyone with a reference to the created <strong>loginDialog</strong> to directly close it (as opposed to explicitly closing it within the dialog). You can see that we change the page by using the previous data value set on the element within <em>_create</em>(). We also dispatch a &#8220;<em>close</em>&#8221; event using <em>_trigger</em>(). The <em>_trigger</em>() method is part of <strong>$.Widget</strong> and can be bound to like other events, yet the type is slightly different within the context of a <strong>widget</strong>. The type value is actually appended to the <strong>widget</strong> name, so if you were to listen for close on this:</p>
<pre class="brush: jscript; title: ;">
$(&quot;#loginSignupDialog&quot;).tmpl().loginDialog().bind( &quot;logindialogclose&quot;, handleLoginDialogClose );
</pre>
<p>That&#8217;s one way to do it, though i often assign handlers by passing in a <strong>callback</strong> object like so:</p>
<pre class="brush: jscript; title: ;">
$(&quot;#loginSignupDialog&quot;).tmpl().loginDialog( {
        close: function( evt, ui ) {
            ...
        }
});
</pre>
<p>We actually trigger two other events within our <strong>loginDialog</strong> &#8211; &#8220;<em>login</em>&#8221; and &#8220;<em>signup</em>&#8221; &#8211; which are dispatched upon submit based on current state. We&#8217;ll see how all this is handled a little later on in more code, but i quickly wanted to touch on something that looks odd in the <em>destroy</em>() override:</p>
<p><em>/_attachments/script/jquery.albums.loginDialog.js</em></p>
<pre class="brush: jscript; title: ;">
var $element = this.element;
var page = $element.find( &quot;div[data-role='content']&quot; );
var submitButton = page.find( &quot;a[aria-label='submit']&quot; );
submitButton.remove();
</pre>
<p>When a form is added top the <strong>DOM</strong> through <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a>, it actually duplicates and hides the originally declared <strong>submit</strong> button and decorates a that duplicate for display. In that decoration, it is given the <strong>aria-label</strong> attribute for accessibility. Not entirely a huge issue, but if you were to show the template form more than once, you would start to see n+ times the amount of submit buttons! So we just remove it in our <em>destroy</em> override and move on.</p>
<p>Alright. Hopefully you are still with me. You may or may not have created your first <a href="http://jquery.com/" target="_blank">jQuery</a> <strong>widget</strong>. Isn&#8217;t it glorious or not glorious, respectively? With our <strong>template</strong> and <strong>widget</strong> defined, now begs the question: <em>When do we show this thing?</em> </p>
<h2>Plugin</h2>
<p>So you thought introducing two new concepts (<a href="http://jquery.com/" target="_blank">jQuery</a> <strong>templates</strong> and <strong>widgets</strong>) was enough for one article? Well, in the words of television&#8217;s <strong>Emeril</strong>, &#8216;<em>We&#8217;re going to kick it up a notch!</em>&#8216; That&#8217;s actually probably a paraphrase. I don&#8217;t know the exact words he said and i don&#8217;t feel like googling it. I was just pandering to the developer crowd who enjoys watching cooking shows&#8230; Its a low point in this article and i am not proud of it. Let&#8217;s keep going.</p>
<p>If we step back and remember why we started doing all this business in this mini-series, we wanted to use validation on operations to our database documents. In the previous article we spoke of <strong>user context</strong>s, and updated our <strong>album</strong> document to require a user field. So, our main intent with this <strong>loginDialog</strong> is to verify a current session and then either login or signup a user. If the session is valid (user previously logged in) then, the user reference is stored and &#8211; dependent on the action &#8211; used in further transactions.</p>
<p>Now, we could just open the <strong>loginDialog</strong> all willy-nilly, here and there, and try to track down the persisted user across actions, but a saner approach (for me at least) is to encapsulate this logic in a <strong>plugin</strong>. You may be familiar with <a href="http://jquery.com/" target="_blank">jQuery</a> <strong>plugins</strong>&#8230; actually we have been using them throughout this whole series. We just haven&#8217;t directly looked at how they are made or work. Like I did with our <strong>widget</strong> example, I am not going to go into a discussion of <a href="http://jquery.com/">jQuery</a> <strong>plugins</strong> per se &#8211; I am going to try and focus on the task at hand and provide explanations as to how it pertains to our application as a whole. That said, to read more about <a href="http://jquery.com/" target="_blank">jQuery</a> <strong>plugins</strong>, this is always a great place to start: <a href="http://docs.jquery.com/Plugins/Authoring" target="_blank">http://docs.jquery.com/Plugins/Authoring</a>.</p>
<p>Alright, we are going to take a little piecemeal approach to fleshing out our <strong>plugin</strong>, explaining as we go along, and I&#8217;ll provide it in its entirety afterward. To start, open up your favorite editor, create a file named <em>jquery.albums.app.js</em> and save it in the <em>/_attachments/script</em> folder of our <strong>albums</strong> <a href="http://couchapp.org/page/index" target="_blank">couchapp</a> directory. Add the following:</p>
<p><em>/_attachments/script/jquery.albums.app.js</em></p>
<pre class="brush: jscript; first-line: 1; title: ;">
(function($) {

  $.albums = $.albums || {};
  $.extend( $.albums, {
  });

})(jQuery)
</pre>
<p>That is the start of our <strong>albums</strong> <strong>plugin</strong> which will be accessible by <strong>$.albums</strong>. We&#8217;re extending our (hopefully) newly created <strong>$.albums</strong> object to flesh out its public <strong>API</strong>. <strong>$.albums</strong> will serve as a facade/adaptor to the <strong>$.couch</strong> plugin and handle the display and event from the <strong>loginDialog</strong>. So there are roughly five main functions of out <strong>$.albums</strong> plugin:</p>
<ul>
<li>Log In &#8211; Direct log in request.</li>
<li>Log Out &#8211; Direct log out request</li>
<li>Save Document &#8211; Request to Create or Update a document.</li>
<li>Delete Document &#8211; Request to Delete a document.</li>
</ul>
<p>The <strong>Log In</strong> and <strong>Log Out</strong> methods mainly interface directly with <strong>$.couch</strong> and won&#8217;t deal with any UI. They are just facades to track the logged in user so we can properly send user data when creating or updating documents. The <strong>Save Document</strong> and <strong>Delete Document</strong> methods are more adaptors for <strong>$.couch</strong> communication &#8211; checking session and presenting the <strong>loginDialog</strong> if necessary. Update the <em>jquery.albums.app.js</em> with the following:</p>
<p><em>/_attachments/script/jquery.albums.app.js</em></p>
<pre class="brush: jscript; first-line: 1; highlight: [6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38]; title: ;">
(function($) {

  $.albums = $.albums || {};
  $.extend( $.albums, {

    dialog: undefined,
    database: undefined,

    logIn: function( name, password, options ) {
      doLogIn( name, password, options );
    },

    logOut: function( options ) {
      doLogOut( options );
    },

    saveDocument: function( document, options ) {
      checkSession( {
        available: function( userCtx ) {
          document.user = user;
          $.albums.database.saveDoc( document, options );
        },
        unavailable: function() {
          showDialog( options );
        }
      });
    },

    deleteDocument: function( document, options ) {
      checkSession( {
        available: function( userCtx ) {
          $.albums.database.removeDoc( document, options );
        },
        unavailable: function() {
          showDialog( options );
        }
      });
    }

  });

})(jQuery)
</pre>
<p>So there we have our 4 public methods of <strong>$.albums</strong>. We have also added to public properties: <strong>dialog</strong> and <strong>database</strong>. These two will be the targets to the <strong>loginDialog</strong> template and a reference to our <strong>albums</strong> database, respectively. This is so we don&#8217;t rely so heavily on globally declared variables to do what we need in our nice little encapsulated <strong>plugin</strong>. In any event, if you have looked at the contents of these methods, they all call other functions that we haven&#8217;t declared yet. Lets start with <em>checkSession</em>() in <strong>saveDocument</strong> and <strong>deleteDocument</strong>. Add the following after the <strong>$.extend</strong> declaration and prior to close of <em>function</em>():</p>
<p><em>/_attachments/script/jquery.albums.app.js</em></p>
<pre class="brush: jscript; title: ;">
function checkSession( options ) {
    options = options || {};
    $.couch.session( {
      success: function( response ) {
        var context = response.userCtx;
        if( context.name == null ) {
          if( options.unavailable ) options.unavailable();
        }
        else{
          if( options.available ) options.available( context );
        }
      },
      error: function( status, error, reason ) {
        if( options.unavailable ) options.unavailable();
      }
    });
}
</pre>
<p>The <em>checkSession</em>() does just that: request the current session established by our client through the <strong>$.couch</strong> plugin. If the <strong>userCtx</strong> comes back as null, there is no session and no logged in user on our end. We can try this out using <strong>curl</strong> on the command line:</p>
<pre class="brush: bash; title: ;">
&gt; curl -vX GET http://127.0.0.1:5984/_session
&lt; {&quot;ok&quot;:true,&quot;userCtx&quot;:{&quot;name&quot;:null,&quot;roles&quot;:[]},&quot;info&quot;:{&quot;authentication_db&quot;:&quot;_users&quot;,&quot;authentication_handlers&quot;:[&quot;oauth&quot;,&quot;cookie&quot;,&quot;default&quot;]}}
</pre>
<p>Depending on the value of <strong>userCtx</strong>, <em>checkSession</em>() will invoke an <em>available</em>() or <em>unavailable</em>() <strong>callback</strong> method on the anonymous options argument. The available responder on <em>saveDocument</em>() and <em>deleteDocument</em>() is different &#8211; one saves, the other deletes &#8211; but if unavailable is entered, they both call <em>showDialog</em>(). Append the following script to <em>jquery.albums.app.js</em> after the <em>checkSession</em>() declaration:</p>
<p><em>/_attachments/script/jquery.albums.app.js</em></p>
<pre class="brush: jscript; title: ;">
function showDialog( options ) {
    $.albums.dialog.loginDialog( {
      login: function( evt, ui ) {
        doLogIn( ui.name, ui.password, {
          success: function( response ) {
            $.albums.dialog.loginDialog( &quot;close&quot; );
          },
          error: function( status, error, reason ) {
            alert( &quot;Error: &quot; + error + &quot;, &quot; + reason );
          }
        });
      },
      signup: function( evt, ui ) {
        doSignUp( ui.name, ui.password, {
          success: function( response ) {
            $.albums.dialog.loginDialog( &quot;close&quot; );
          },
          error: function( status, error, reason ) {
            alert( &quot;Error: &quot; + error + &quot;, &quot; + reason );
          }
        });
      }
    });
}
</pre>
<p>Hey! That&#8217;s using our <strong>widget</strong>! I don&#8217;t know why i seriously get excited when i see that&#8230; In any event, there it is in all its glory. The <strong>login template</strong> will be handed to <strong>$.albums</strong> and we&#8217;ll widget-ize it within the <em>showDialog</em>() invocation:</p>
<pre class="brush: jscript; title: ;">
$.albums.dialog.loginDialog( {
...
});
</pre>
<p>If you remember back when we created the <strong>widget</strong>, it will dispatch two events when submitted based on state: <em>login</em> and <em>signup</em>. Here we have added the <strong>callbacks</strong> to those events which in turn call either <em>doLogIn</em>() or <em>doSignUp</em>(). We&#8217;ll get to that in a bit, but i wanted to point out the success responders in the anonymous <strong>callback</strong> objects we pass to those methods:</p>
<pre class="brush: jscript; title: ;">
success: function( response ) {
    $.albums.dialog.loginDialog( &quot;close&quot; );
}
</pre>
<p>If we have passed being logged in/signed up, we close the <strong>loginDialog</strong>. We exposed the <em>close</em>() method in <em>jquery.albums.loginDialog.js</em>, but its important to note that you cannot call <em>close</em>() using dot-notation like a property. The reason is that we are not holding a reference to the <strong>loginDialog</strong>. Calling <strong>$(&#8221;#myElement&#8221;)</strong>.<em>loginDialog</em>() just decorates the target element on the <strong>DOM</strong>. We can still interface with <strong>$(&#8221;#myElement&#8221;)</strong> but those methods associated with the <strong>widget</strong> are not then accessible on the target element. So we call a public method through <em>loginDialog</em>().</p>
<p>OK. So <em>doLogin</em>(), <em>doLogout</em>() and <em>doSignUp</em>() are yet to be covered. For some reason i have this convention where if it is considered an internal response to a public invocation i prepend &#8216;<em>d</em>o&#8217; to the public method name. Some people prefer &#8220;<em>_</em>&#8220;. To each his own. Just if you are wondering&#8230; Let&#8217;s tackle the login and logout first, as they are easy. Add the following script to <em>jquery.albums.app.js</em> somewhere after the <strong>$.extend</strong> declaration and prior to the end of the <em>function</em>() block:</p>
<p><em>/_attachments/script/jquery.albums.app.js</em></p>
<pre class="brush: jscript; title: ;">
var user; /* _user &gt; document.name */

function doLogIn( name, password, options ) {
    options = options || {};
    var loginObj = {
      name:name,
      password:password,
      success: function( response ) {
        user = response.name;
        if( options.success ) options.success( response );
      },
      error: function( status, error, reason ) {
        if( options.error ) options.error( status, error, reason );
      }
    };
    $.couch.login( loginObj );
}

function doLogOut( options ) {
    options = options || {};
    $.couch.logout( {
      success: function( response ) {
        user = undefined;
        if( options.success ) options.success( response );
      },
      error: function( status, error, reason ) {
        if( options.error ) options.error( status, error, reason );
      }
    })
}
</pre>
<p>Again, we are just interfacing with the <strong>$.couch</strong> plugin to perform the <em>login</em>() and <em>logout</em>(). The only reason we go through <strong>$.albums</strong> instead of <strong>$.couch</strong> directly is to maintain the <strong>user</strong>, which we have privately declared. That user value is the one assigned to the user field of a document when a new <strong>album</strong> document will be created and saved through <strong>$.albums</strong> using <em>saveDocument</em>().</p>
<p>Alright, <strong>Sign Up</strong> is where the magic happens. Signing a user up through <strong>$.couch</strong> is a little trickier. In <a href="http://127.0.0.1:5984/_utils" target="_blank">Futon</a> it is all easy-peasy as we saw in the last article in this mini-series in a series. Now that we have taken our <a href="http://couchdb.apache.org/" target="_blank">CouchDB</a> instance out of <strong>Admin Party</strong> mode, the <strong>$.couch</strong>.<em>signUp</em>() method won&#8217;t work unless we are logged in as an admin. We don&#8217;t want to take the approach of <a href="http://127.0.0.1:5984/_utils" target="_blank">Futon</a> for the User Experience for our little application here. Our application shouldn&#8217;t act as an admin console to the <a href="http://couchdb.apache.org/" target="_blank">CouchDB</a> database as well as its current function of just adding, updating and deleting <strong>album</strong> documents. </p>
<p>We going to secretly log in as an admin behind the scenes and set our new user up for gold and start adding documents. So, <strong>Sign Up</strong> is actually going to be a series of commands just to sign someone up, assign their proper <strong>user-role</strong> and create their session to allow them to start working with <strong>album</strong> documents. That sequence in readable terms is:</p>
<ol>
<li>Log In as Admin</li>
<li>Sign Up new User</li>
<li>Open new User document</li>
<li>Add &#8220;albums-user&#8221; User Role to new User</li>
<li>Log Out as Admin</li>
<li>Log In as new User</li>
</ol>
<p>Maybe the <em>jquery.couch</em> plugin has changed since the last revision i checked out, but that is the order of things to <em>signup</em> and <em>login</em> a new user as far as i understand. The signature for <strong>$.couch</strong>.<em>signUp</em>() method has no arguments for administration to do this more streamlined, so we are going to create a chain of commands to signup a new user a little more efficiently. Now, in actuality, i would turn to a server-side developer and ask pretty-please that they implement a proxy in whatever language to do this and not handle it all in <strong>JavaScript</strong> (especially since we are going to expose our admin credentials &#8211; <em>HIDE YOUR CHILDREN</em>!), but we&#8217;re having fun and not going to production with this, right? We&#8217;re taking some liberties to explore what we have&#8230;</p>
<p>Now, if you have not figured out yet in following these articles, i can get a little anal. But it isn&#8217;t about everything. I seem to get focused on one thing that really irks me. And one of those things is deeply nested anonymous <strong>callbacks</strong>. Sure i am guilty of doing it and when i do it i feel dirty, but i usually let it go if its not nesting too deep. This sequence of actions for <strong>Sign Up</strong>, however, i can foresee being really ugly if we just went with anonymous <strong>callback</strong> objects down the line. So what i did was create <strong>Queue</strong> and <strong>Command</strong> &#8220;classes&#8221; to keep my sanity. The following is the script for that. Open a new document in your favorite editor (we&#8217;ll get back to <em>jquery.albums.app.js</em> in a bit) and save the following script as <em>command_queue.js</em> in <em>/_attachments/script</em>:</p>
<p><em>/_attachments/script/command_queue.js</em></p>
<pre class="brush: jscript; first-line: 1; title: ;">
(function(window) {

    function Commandable() {}
    Commandable.prototype.execute = function( data ){};

    function Queue( ops ) {
        this.options = ops || {};
        this.list = [];
        this.command;

        this.addCommand = function( command ) {
            var length = this.list.length;
            if( length &gt; 0 ) {
                this.list[length-1].nextCommand = this;
            }
            this.list.push( command );
        }
    }
    var q = Queue.prototype = new Commandable();
    q.options = undefined;
    q.list = undefined;
    q.command = undefined;
    q.constructor = Queue;
    q.execute = function( data ) {
        if( this.list.length &gt; 0 ) {
            this.command = this.list.shift();
            this.command.execute( data );
        }
        else {
            this.command = undefined;
            if( this.options.complete ) {
                this.options.complete();
            }
        }
    }

    function Command( target, args, ops ) {
        this.target = target;
        this.args = args || [];
        this.options = ops || {};
        this.nextCommand = undefined;
    }
    var c = Command.prototype = new Commandable();
    c.constructor = Command;
    c.getCommandOptions = function( options, nextCommand ) {
        var responder = {
            ops: options,
            success: function( response ) {
                if( options &amp;&amp; options.success ) options.success( response );
                if( nextCommand ) {
                    nextCommand.execute( response );
                }
            },
            error: function( status, error, reason ) {
                if( options &amp;&amp; options.error ) options.error( status, error, reason );
            }
        };
        return $.extend( {}, this.options, responder );
    }
    c.execute = function( data ) {
        this.args.push( this.getCommandOptions( this.options, this.nextCommand ) );
        this.target.apply( this, this.args );
    }

window.Queue = Queue;
window.Command = Command;

}(window));
</pre>
<p>I&#8217;m not going to say it&#8217;s sophisticated by any means, but this is a simple implementation to allow us to chain commands together. That is done by adding <strong>Commands</strong> to the <strong>Queue</strong> using <em>addCommand</em>(), which then appends a command using the <em>nextCommand</em> property of the previous (if available) <strong>Command</strong>. Both <strong>Queue</strong> and <strong>Command</strong> have a method called <em>execute</em>() (as extensions of <strong>Commandable</strong>). Executing a <strong>Queue</strong> will start the chain of commands; executing a <strong>Command</strong> will invoke whatever <strong>target</strong> method supplied in the constructor. If this needs more explanation, please leave a comment. We&#8217;ll see how we use this by implementing our <em>doSignUp</em>() method in <em>jquery.albums.app.js</em>. Open up <em>jquery.albums.app.js</em> in your favorite editor and add the following script somewhere after the <strong>$.execute</strong> declaration and before the end of the <em>function</em>() block:</p>
<p><em>/_attachments/script/jquery.albums.app.js</em></p>
<pre class="brush: jscript; title: ;">
function doSignUp( name, password, options ) {
    options = options || {};
    var queueOptions = {
      complete: function() {
        if( options.success ) options.success();
      }
    }
    var queue = new Queue( queueOptions );
    queue.addCommand( new Command( $.albums.logIn, [&quot;toddanderson&quot;, &quot;admin123&quot;] ) );
    queue.addCommand( new Command( $.couch.signup, [{name:name}, password] ) );
    queue.addCommand( new OpenUserDocCommand() );
    queue.addCommand( new AssignRoleCommand() );
    queue.addCommand( new Command( $.albums.logOut ) );
    queue.addCommand( new Command( $.albums.logIn, [name, password], options ) );
    queue.execute();
}
</pre>
<p>There we have our sequence of command described earlier. You can see how we pass the target method and arguments to the <strong>Command</strong> to be executed and the queue of commands is assembled using <strong>Queue</strong>:<em>addCommand</em>(). Again, our admin credentials are exposed and available to all &#8211; I do not recommend this practice in real life. Its just us here. So, there are two commands there in the middle that we haven&#8217;t discussed and aren&#8217;t declared in <em>command_queue.js</em>. They are specific to our <strong>albums</strong> application, so we will define them in <em>jquery.albums.app.js</em>. With the file still open, add the following script after (or before) the <em>doSignUp</em>() declaration:</p>
<p><em>/_attachments/script/jquery.albums.app.js</em></p>
<pre class="brush: jscript; title: ;">
function OpenUserDocCommand( target, args, options ) {}
OpenUserDocCommand.prototype = new Command();
OpenUserDocCommand.prototype.execute = function( data ) {
      var $userDB = $.couch.db(&quot;_users&quot;);
      $userDB.openDoc( data.id, this.getCommandOptions( this.options, this.nextCommand ) );
}

function AssignRoleCommand( target, args, options ) {}
AssignRoleCommand.prototype = new Command();
AssignRoleCommand.prototype.execute = function( data ) {
      data.roles = [&quot;albums-user&quot;];
      var $userDB = $.couch.db(&quot;_users&quot;);
      $userDB.saveDoc( data, this.getCommandOptions( this.options, this.nextCommand ) );
}
</pre>
<p>Nothing too crazy going on in <strong>OpenUserDocCommand</strong> or <strong>AssignRoleCommand</strong>, just needed to do some work with the <strong>_users</strong> database of our <a href="http://couchdb.apache.org/" target="_blank">CouchDB</a> instance as an admin.</p>
<p>Guess what? That&#8217;s it! We&#8217;re done with <em>jquery.albums.app.js</em>. Whew! If you have stuck around, i am quite humbled. Seriously. A lot of code and rambling on. I don&#8217;t know if i would have made it. Anyway, here is <em>jquery.albums.app.js</em> in full:</p>
<p><em>/_attachments/script/jquery.albums.app.js</em></p>
<pre class="brush: jscript; first-line: 1; title: ;">
(function($) {

  $.albums = $.albums || {};
  $.extend( $.albums, {

    dialog: undefined,
    database: undefined,

    logIn: function( name, password, options ) {
      doLogIn( name, password, options );
    },

    logOut: function( options ) {
      doLogOut( options );
    },

    saveDocument: function( document, options ) {
      checkSession( {
        available: function( userCtx ) {
          document.user = user;
          $.albums.database.saveDoc( document, options );
        },
        unavailable: function() {
          showDialog( options );
        }
      });
    },

    deleteDocument: function( document, options ) {
      checkSession( {
        available: function( userCtx ) {
          $.albums.database.removeDoc( document, options );
        },
        unavailable: function() {
          showDialog( options );
        }
      });
    }

  });

  var user; /* _user &gt; document.name */

  function OpenUserDocCommand( target, args, options ) {}
  OpenUserDocCommand.prototype = new Command();
  OpenUserDocCommand.prototype.execute = function( data ) {
      var $userDB = $.couch.db(&quot;_users&quot;);
      $userDB.openDoc( data.id, this.getCommandOptions( this.options, this.nextCommand ) );
  }

  function AssignRoleCommand( target, args, options ) {}
  AssignRoleCommand.prototype = new Command();
  AssignRoleCommand.prototype.execute = function( data ) {
      data.roles = [&quot;albums-user&quot;];
      var $userDB = $.couch.db(&quot;_users&quot;);
      $userDB.saveDoc( data, this.getCommandOptions( this.options, this.nextCommand ) );
  }

  function checkSession( options ) {
    options = options || {};
    $.couch.session( {
      success: function( response ) {
        var context = response.userCtx;
        if( context.name == null ) {
          if( options.unavailable ) options.unavailable();
        }
        else{
          if( options.available ) options.available( context );
        }
      },
      error: function( status, error, reason ) {
        if( options.unavailable ) options.unavailable();
      }
    });
  }

  function doLogIn( name, password, options ) {
    options = options || {};
    var loginObj = {
      name:name,
      password:password,
      success: function( response ) {
        user = response.name;
        if( options.success ) options.success( response );
      },
      error: function( status, error, reason ) {
        if( options.error ) options.error( status, error, reason );
      }
    };
    $.couch.login( loginObj );
  }

  function doLogOut( options ) {
    options = options || {};
    $.couch.logout( {
      success: function( response ) {
        user = undefined;
        if( options.success ) options.success( response );
      },
      error: function( status, error, reason ) {
        if( options.error ) options.error( status, error, reason );
      }
    })
  }

  function doSignUp( name, password, options ) {
    options = options || {};
    var queueOptions = {
      complete: function() {
        if( options.success ) options.success();
      }
    }
    var queue = new Queue( queueOptions );
    queue.addCommand( new Command( $.albums.logIn, [&quot;toddanderson&quot;, &quot;admin123&quot;] ) );
    queue.addCommand( new Command( $.couch.signup, [{name:name}, password] ) );
    queue.addCommand( new OpenUserDocCommand() );
    queue.addCommand( new AssignRoleCommand() );
    queue.addCommand( new Command( $.albums.logOut ) );
    queue.addCommand( new Command( $.albums.logIn, [name, password], options ) );
    queue.execute();
  }

  function showDialog( options ) {
    $.albums.dialog.loginDialog( {
      login: function( evt, ui ) {
        doLogIn( ui.name, ui.password, {
          success: function( response ) {
            $.albums.dialog.loginDialog( &quot;close&quot; );
          },
          error: function( status, error, reason ) {
            alert( &quot;Error: &quot; + error + &quot;, &quot; + reason );
          }
        });
      },
      signup: function( evt, ui ) {
        doSignUp( ui.name, ui.password, {
          success: function( response ) {
            $.albums.dialog.loginDialog( &quot;close&quot; );
          },
          error: function( status, error, reason ) {
            alert( &quot;Error: &quot; + error + &quot;, &quot; + reason );
          }
        });
      }
    });
  }

})(jQuery)
</pre>
<p>Now before you run off, kiss your significant other and tell him/her that you will soon be billionaires, we have a little more work to do to get this up and running in our <strong>Albums</strong>  application.</p>
<h2>Loader and Index</h2>
<p>We kind of went off the deep-end there and dove right into code that code stand on its own outside of our current design of the <strong>Albums</strong> application. That&#8217;s good, but now we gotta reel it back in and wire it up. To start, lets add our new scripts in the <em>loader</em>. Open up <em>/vendor/couchapp/_attachments/loader.js</em> and save the following modifications:</p>
<p><em>/vendor/couchapp/_attachments/loader.js</em></p>
<pre class="brush: jscript; first-line: 1; highlight: [18,19,20]; title: ;">
function couchapp_load(scripts) {
  for (var i=0; i &lt; scripts.length; i++) {
    document.write('&lt;script src=&quot;'+scripts[i]+'&quot;&gt;&lt;\/script&gt;')
  };
};

couchapp_load([
  &quot;/_utils/script/sha1.js&quot;,
  &quot;/_utils/script/json2.js&quot;,
  &quot;vendor/couchapp/jquery-1.4.4.js&quot;,
  &quot;/_utils/script/jquery.couch.js&quot;,
  &quot;vendor/couchapp/jquery.couch.app.js&quot;,
  &quot;vendor/couchapp/jquery.couch.app.util.js&quot;,
  &quot;vendor/couchapp/jquery.mustache.js&quot;,
  &quot;vendor/couchapp/jquery.evently.js&quot;,
  &quot;vendor/couchapp/jquery.mobile-1.0a2.js&quot;,
  &quot;vendor/couchapp/jquery.tmpl.js&quot;,
  &quot;script/command_queue.js&quot;,
  &quot;script/jquery.albums.app.js&quot;,
  &quot;script/jquery.albums.loginDialog.js&quot;
]);
</pre>
<p>We&#8217;ve just added the last three files we have been working on: the <em>command_queue</em> script and our <strong>$.albums</strong> plugin and <strong>loginDialog</strong> widget. Now we&#8217;re going to make some modifications to the inline script on our <em>index.html</em> document. In a <a href="http://custardbelly.com/blog/?p=332" target="_blank">previous article</a> we hooked up the saving of a new album document to the internal <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a> <strong>addAlbum</strong> page, and were using the <em>jquery.couch</em> plugin directly to save the document. Now we are just going to go through our <strong>$.albums</strong> plugin to perform that action which will open the <strong>loginDialog</strong> if a session is currently not available on our client. Open the <em>/_attachments/index.html</em> file in your favorite editor and save the following modifications in the <em>handleDocumentReady</em>() function:</p>
<p><em>/attachments/index.html</em></p>
<pre class="brush: jscript; first-line: 79; highlight: [84,85,86,87,88,97]; title: ;">
function handleDocumentReady()
{
    $(&quot;#home&quot;).bind( &quot;pagebeforeshow&quot;, refreshAlbums );
    refreshAlbums();

    // Set database reference and dialog template on albums.
    $.extend( $.albums, {
        database: $db,
        dialog:  $(&quot;#loginSignupDialog&quot;).tmpl()
    });

    $(&quot;#addSubmitButton&quot;).live( &quot;click&quot;, function( event ) {
        event.preventDefault();
        var document = {};
        document.artist = $(&quot;input#addArtistField&quot;).val();
        document.title = $(&quot;input#addTitleField&quot;).val();
        document.description = $(&quot;textarea#addDescriptionField&quot;).val();
        document.creation_date = ( new Date() ).getTime();
        $.albums.saveDocument( document, {
            success: function() {
                $.mobile.changePage( &quot;#home&quot;, &quot;slidedown&quot;, true, true );
            },
            error: function( status, error, reason ) {
                alert( &quot;Cannot save new document.\n&quot; + status + &quot;, &quot; + reason + &quot;, &quot; + error );
            }
        });
        return false;
    });

    $(&quot;#addAlbum&quot;).bind( &quot;pagehide&quot;, function() {
        $(&quot;input#addArtistField&quot;).val( &quot;&quot; );
        $(&quot;input#addTitleField&quot;).val( &quot;&quot; );
        $(&quot;textarea#addDescriptionField&quot;).val( &quot;&quot; );
    });
}
</pre>
<p>Not that much to change. First we assign the default properties for the dialog <strong>template</strong> and database reference for our <strong>$.albums</strong> plugin and then we replace the call to save the document using <em>jquery.couch</em> to that of our <strong>$.albums</strong> plugin. Ta-da! Now we can add new documents as a logged in user.</p>
<p>There is, however, two more places that we need to interact with our <strong>$.albums</strong> plugin: the <strong>edit</strong> page and the <strong>delete</strong> page. Without modifying those and with the new authorization and validation we have introduced, we&#8217;d only be able to create and read documents&#8230; </p>
<p><em>Oh nos! There are tons of albums that i entered in late at night in a different state of mind! I am second guessing my decision on wanting <strong>Hall &#038; Oates</strong>&#8216;</em> War Babies! </p>
<p>These are the type of exclamations i am assuming are going through your head&#8230; because i would never&#8230;</p>
<h2>album-delete and album-edit</h2>
<p>If you go way back in this article series and have been following along, you may remember that we create quasi-view controllers for our <a href="http://couchapp.org/page/index" target="_blank">couchapp</a> <strong>template</strong> pages and included the as <strong>partials</strong> in the <strong>show function</strong>. There are two that we need to modify with our recent changes to using the <strong>$.albums</strong> plugin to verify session: <em>/_attachments/script/album-delete-dialog.js</em> and <em>/_attachments/script/album-edit-page.js</em>. They will be small changes, but once deployed will give our application a little more security on who can perform modifications on <strong>album</strong> documents.</p>
<p>Open up <em>/_attachments/script/album-delete-dialog.js</em> in your favorite editor and save the following change to the <em>handleDelete</em>() function:</p>
<p><em>/_attachments/script/album-delete-dialog.js</em></p>
<pre class="brush: jscript; first-line: 32; highlight: [40]; title: ;">
function handleDelete( event )
{
    event.preventDefault();
    var docId = $(&quot;#dialogContent&quot;).data(&quot;identity&quot;);
    // First open doc based on ID in order to get full document.
    $db.openDoc( docId, {
        success: function( document ) {
            // Then use the opened doc as reference to remove.
            $.albums.deleteDocument( document, {
                success: function() {
                    $.mobile.changePage( &quot;#home&quot;, &quot;slide&quot;, true, true );
                },
                error: function() {
                    alert( &quot;Could not remove document with id: &quot; + docId );
                }
            });
        },
        error: function() {
            alert( &quot;Could not find document with id: &quot; + docId );
        }
    });
    return false;
}
</pre>
<p>Open up <em>/_attachments/script/album-edit-page.js</em> in your favorite editor and save the following change to <em>saveDocument</em>():</p>
<p><em>/_attachments/script/album-edit-page.js</em></p>
<pre class="brush: jscript; first-line: 42; highlight: [44]; title: ;">
function saveDocument( document )
{
    $.albums.saveDocument( document, {
        success: function( response )  {
            updateEditableAlbum( document );
            navigateToAlbumPage( document._id );
        },
        error: function( status, error, reason ) {
            alert( &quot;Cannot save document: &quot; + document._id + &quot;\n&quot; + reason );
        }
    });
}
</pre>
<p>That&#8217;s all! basically moved away from actions through the reference to our <strong>albums</strong> database to using the <strong>$.albums</strong> plugin. Finally. Now let&#8217;s push all this to our <a href="http://couchdb.apache.org/" target="_blank">CouchDB</a> instance so we can play around with it.</p>
<h2>Deployment</h2>
<p>If you remember from the last article when we introduced authorization, we need to pass our credentials when we push our couchapp to the <a href="http://couchdb.apache.org/" target="_blank">CouchDB</a> instance:</p>
<pre class="brush: bash; title: ;">
couchapp push albums http://toddanderson:admin123@127.0.0.1:5984/albums
</pre>
<p>You&#8217;ll will have to replace to username and password, but once we have pushed we can now checkout our application at <a href="http://127.0.0.1:5984/albums/_design/albums/index.html" target="_blank">http://127.0.0.1:5984/albums/_design/albums/index.html</a>. If you visit your application and try to either add, edit or delete a document and have not previously logged in, you will see something on the following:</p>
<p><img src="http://www.custardbelly.com/blog/images/couchapp_7_2_2.png" alt="Log In" /><br />
<em>[Log In]</em></p>
<p><img src="http://www.custardbelly.com/blog/images/couchapp_7_2_1.png" alt="Log In" /><br />
<em>[Sign Up]</em></p>
<h2>Conclusion</h2>
<p>We have come a long way! We now have authorization and user validation in our <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a> <strong>albums</strong> application ensuring that a user must be logged in to create a new <strong>album</strong> document and that the owner of a document is the only one that can make modifications or delete the document from the database. Fun stuff.</p>
<p>I think this is going to be the last article of this series. Of course if this application were to go live, it would need a lot more work. For instance, the ability to log in and log out persisted on every page and information about who is logged in, etc. &#8211; but i will leave that up to you if you want to keep going. Hope you had fun and gleaned some useful information that i hope is not misleading.</p>
<p>Thanks again if you have actually took the time to follow along in this series. I am truly humbled if you sat through it all.</p>
<p>Cheers!</p>
<p><em>[Note] This post was written against the following software versions:</em><br />
<strong>CouchDB </strong>– 1.0.1<br />
<strong>CouchApp</strong> – 0.7.2<br />
<strong>jQuery</strong> – 1.4.4<br />
<strong>jQuery Mobile</strong> – 1.0a2<br />
<strong>jQuery Templates Plugin</strong> 1.0.0pre<br />
<em>If you have found this post and any piece has moved forward, hopefully the examples are still viable/useful. I will not be updating the examples in this post in parellel with updates to any of the previously mentioned software, unless explicitly noted.</em></p>
<p><strong>Articles in this series:</strong></p>
<ol>
<li><a href="http://custardbelly.com/blog/?p=244" target="_blank">Getting Started</a></li>
<li><a href="http://custardbelly.com/blog/?p=278" target="_blank">Displaying a page detail of a single album.</a></li>
<li><a href="http://custardbelly.com/blog/?p=297" target="_blank">Templates and Mustache</a></li>
<li><a href="http://custardbelly.com/blog/?p=318" target="_blank">Displaying an editable page of an album.</a></li>
<li><a href="http://custardbelly.com/blog/?p=332" target="_blank">Creating and Adding an album document.</a></li>
<li><a href="http://custardbelly.com/blog/?p=344" target="_blank">Deleting an album document</a></li>
<li><a href="http://custardbelly.com/blog/?p=360" target="_blank">Authorization and Validation &#8211; Part 1</a></li>
<li><a href="http://custardbelly.com/blog/?p=394">Authorization and Validation &#8211; Part 2</a></li>
</ol>
<p><a href="http://custardbelly.com/downloads/couchapp/jqm_couchdb_albums.zip">Full source for albums couchapp available here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://custardbelly.com/blog/2011/03/04/jquery-mobile-couchdb-part-7-2-%e2%80%93-authorization-and-validation/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

