<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.3.3" -->
<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/"
	>

<channel>
	<title>SitePen Blog</title>
	<link>http://www.sitepen.com/blog</link>
	<description>SitePen Services and notes about Dojo, DWR, Cometd, JavaScript, and the Web</description>
	<pubDate>Wed, 24 Jun 2009 15:07:55 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.3.3</generator>
	<language>en</language>
			<item>
		<title>Unobtrusive JavaScript Typing via JSON Schema Interfaces</title>
		<link>http://www.sitepen.com/blog/2009/06/23/unobtrusive-javascript-typing-via-json-schema-interfaces/</link>
		<comments>http://www.sitepen.com/blog/2009/06/23/unobtrusive-javascript-typing-via-json-schema-interfaces/#comments</comments>
		<pubDate>Tue, 23 Jun 2009 17:05:56 +0000</pubDate>
		<dc:creator>Kris Zyp</dc:creator>
		
		<category><![CDATA[Dojo]]></category>

		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/2009/06/23/unobtrusive-javascript-typing-via-json-schema-interfaces/</guid>
		<description><![CDATA[One of the frequently expressed frustrations with JavaScript, especially from users coming from more static languages, is the lack of typing capabilities in JavaScript. Typing provides the ability to define and enforce contracts between interfaces such that interactions can be validated before violated assumptions result in later difficult-to-find bugs. On the other hand, many users [...]]]></description>
			<content:encoded><![CDATA[<p>One of the frequently expressed frustrations with JavaScript, especially from users coming from more static languages, is the lack of typing capabilities in JavaScript. Typing provides the ability to define and enforce contracts between interfaces such that interactions can be validated before violated assumptions result in later difficult-to-find bugs. On the other hand, many users that have grown fond of JavaScript have come to enjoy the fast and free style, and the minimalism of simply defining behavior without needing to make extra type definitions. However, these two coding preferences do not need to be mutually exclusive. </p>
<p>The abandoned <a href="http://www.ecmascript.org/es4/spec/overview.pdf">ES4 effort</a> made a valiant attempt to <a href="http://www.ecmascript.org/es4/spec/evolutionary-programming-tutorial.pdf">add typing</a> (without losing dynamism) via <a href="http://lambda-the-ultimate.org/node/2061">gradual typing</a>; however this still demanded the inclusion of intrusive typing annotations&mdash;thus adding type constraints to code polluted the otherwise simple direct JavaScript programming style necessitating more complex, difficult-to-follow code. Other <a href="http://webreflection.blogspot.com/2007/05/javastrict-act-iii-documentation-and.html">efforts</a> <a href="http://webreflection.blogspot.com/2007/05/javastrict-strict-type-arguments.html">include libraries</a> to define types on functions without extending syntax.</p>
<p>It is now possible to unobtrusively define type constraints on properties and methods in JavaScript with portable <a href="http://www.json-schema.org/">JSON schema</a> based definitions called JSON schema interfaces (JSI). JSI is a typing system for JavaScript that does not force any new syntax on JavaScript. Schema structures can be used to define the type constraints in a way that works with existing JavaScript classes and objects. </p>
<p>The new typing module can be used both as a standalone bundle (with the <a href="http://code.google.com/p/jsonschema/downloads/list">JavaScript JSON schema library</a>) which can be <a href="http://www.sitepen.com/labs/code/typed/typed.zip">downloaded now</a>. It also can be used as a Dojo module, available as <code>dojox.lang.typed</code>. Adding type constraints to JavaScript classes is very simple; the type constraints follow the JSON schema structure, where the class acts as the root of the schema. One can define property constraints in the <code>properties</code> property. The JSI extension to standard JSON schemas also allows method signatures to be defined in the <code>methods</code> property, with the ability to define the types for parameters and return values.</p>
<h2>Using Typed Classes</h2>
<p>To demonstrate, first we will create a normal JavaScript class using the standard prototype pattern:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">Balloon = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>diameter<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">diameter</span> = diameter;
<span style="color: #66cc66;">&#125;</span>;
Balloon.<span style="color: #006600;">prototype</span> = <span style="color: #66cc66;">&#123;</span>
  getVolume: <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
     <span style="color: #000066; font-weight: bold;">return</span> Math.<span style="color: #006600;">pow</span><span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">diameter</span>, <span style="color: #CC0000;">3</span><span style="color: #66cc66;">&#41;</span> * Math.<span style="color: #006600;">PI</span> / <span style="color: #CC0000;">6</span>;
  <span style="color: #66cc66;">&#125;</span>,
  setVolume: <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>volume<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
     <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">diameter</span> = Math.<span style="color: #006600;">pow</span><span style="color: #66cc66;">&#40;</span>volume * <span style="color: #CC0000;">6</span> <span style="color: #0066FF;">/ Math.<span style="color: #006600;">PI</span>, <span style="color: #CC0000;">1</span>/</span><span style="color: #CC0000;">3</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>;</pre></div></div>

<p>This class should work fine on its own, but if we want to define constraints to ensure that its interface is properly exposed and used as expected, we can declare the class as typed and add type constraints. Using the standalone library, we first define the class as type-able:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">Balloon = typed<span style="color: #66cc66;">&#40;</span>Balloon<span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>And now we can define constraints:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">Balloon.<span style="color: #006600;">properties</span> = <span style="color: #66cc66;">&#123;</span>
  diameter:<span style="color: #66cc66;">&#123;</span>
     type:<span style="color: #3366CC;">&quot;number&quot;</span>,
     minimum: <span style="color: #CC0000;">0</span>,
     description:<span style="color: #3366CC;">&quot;This is the diameter of the balloon&quot;</span>
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>;</pre></div></div>

<p>Now we can try out our constraints:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #009900; font-style: italic;">// this will work normally</span>
goodBalloon = <span style="color: #003366; font-weight: bold;">new</span> Balloon<span style="color: #66cc66;">&#40;</span><span style="color: #CC0000;">2</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #009900; font-style: italic;">// this will throw a TypeError because the diameter must be a number</span>
goodBalloon.<span style="color: #006600;">diameter</span> = <span style="color: #3366CC;">&quot;not a number&quot;</span>;
<span style="color: #009900; font-style: italic;">// this will throw a TypeError as it results in an invalid value for the diameter</span>
badBalloon = <span style="color: #003366; font-weight: bold;">new</span> Balloon<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;not a number&quot;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #009900; font-style: italic;">// this will throw a TypeError because the diameter must be at least zero.</span>
goodBalloon.<span style="color: #006600;">diameter</span> = <span style="color: #CC0000;">-10</span>;</pre></div></div>

<p>This is effectively JSON schema applied to JavaScript objects with live constraints. Rather than just validating the state of the object at some point in time, properties are kept valid throughout the life of the object. Notice also that the property definition we created only constrains a single property; any other properties can be added or removed from the object freely. Schemas are additive in their constraints; an empty schema does not enforce any constraints on an object, and it can take any form.</p>
<p>However, JSI takes us beyond just constraining properties. We can also constrain the calls to methods. To do this, we can create method definitions in a similar way that we create property definitions in a schema. </p>
<p>A method definition has two important attributes: <code>parameters</code> and <code>returns</code>. The <code>parameters</code> attribute takes an array which defines the type for each parameter value to be passed to the method by position. The <code>returns</code> attribute takes a schema/type definition to constrain what values can be returned by the method. We could define types on the methods that the class implements (those defined on the prototype):</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">Balloon.<span style="color: #006600;">methods</span> = <span style="color: #66cc66;">&#123;</span>
  setVolume:<span style="color: #66cc66;">&#123;</span>
    parameters:<span style="color: #66cc66;">&#91;</span>
      <span style="color: #66cc66;">&#123;</span>
         type:<span style="color: #3366CC;">&quot;number&quot;</span>,
         minimum: <span style="color: #CC0000;">0</span>,
         description:<span style="color: #3366CC;">&quot;The new volume for the balloon.&quot;</span>
       <span style="color: #66cc66;">&#125;</span>
     <span style="color: #66cc66;">&#93;</span>,
     description: <span style="color: #3366CC;">&quot;Set the volume (changes the diameter property)&quot;</span>
  <span style="color: #66cc66;">&#125;</span>,
  getVolume:<span style="color: #66cc66;">&#123;</span>
    parameters:<span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>,
    returns:<span style="color: #66cc66;">&#123;</span>
       type:<span style="color: #3366CC;">&quot;number&quot;</span>,
       minimum: <span style="color: #CC0000;">0</span>,
       description:<span style="color: #3366CC;">&quot;The volume of the balloon.&quot;</span>
     <span style="color: #66cc66;">&#125;</span>  
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>;</pre></div></div>

<p>Now we can try out the method definitions:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #009900; font-style: italic;">// create a new balloon:</span>
goodBalloon = <span style="color: #003366; font-weight: bold;">new</span> Balloon<span style="color: #66cc66;">&#40;</span><span style="color: #CC0000;">2</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #009900; font-style: italic;">// will work properly</span>
goodBalloon.<span style="color: #006600;">setVolume</span><span style="color: #66cc66;">&#40;</span><span style="color: #CC0000;">10</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #009900; font-style: italic;">// this will throw a TypeError</span>
goodBalloon.<span style="color: #006600;">setVolume</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;big&quot;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>We can also define class inheritance with our schemas, as well as utilize composition for property and method definitions. Suppose we had defined a subclass of Balloon called ColoredBalloon:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #003366; font-weight: bold;">function</span> ColoredBalloon<span style="color: #66cc66;">&#40;</span>color<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">color</span> = color;
<span style="color: #66cc66;">&#125;</span>
ColoredBalloon.<span style="color: #006600;">prototype</span> = <span style="color: #003366; font-weight: bold;">new</span> Balloon<span style="color: #66cc66;">&#40;</span><span style="color: #CC0000;">0</span><span style="color: #66cc66;">&#41;</span>;
ColoredBalloon = typed<span style="color: #66cc66;">&#40;</span>ColoredBalloon<span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>We can define the inheritance structure in our schema when we define the schema for the subclass:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">ColoredBalloon<span style="color: #66cc66;">&#91;</span><span style="color: #3366CC;">&quot;extends&quot;</span><span style="color: #66cc66;">&#93;</span> = Balloon;</pre></div></div>

<p>We can use composition for our property definitions. If we have another class called <code>Color</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #003366; font-weight: bold;">function</span> Color<span style="color: #66cc66;">&#40;</span>red, green, blue<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
   ...
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>We could define a color property for our ColoredBalloon class that takes Color instances:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">ColoredBalloon.<span style="color: #006600;">properties</span> = <span style="color: #66cc66;">&#123;</span>
  color: Color
<span style="color: #66cc66;">&#125;</span>;</pre></div></div>

<p>Now we can try our color property:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">balloon = <span style="color: #003366; font-weight: bold;">new</span> ColoredBalloon<span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">new</span> Color<span style="color: #66cc66;">&#40;</span><span style="color: #CC0000;">33</span>,<span style="color: #CC0000;">44</span>,<span style="color: #CC0000;">55</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #009900; font-style: italic;">// assign a color, this should work</span>
balloon.<span style="color: #006600;">color</span> = <span style="color: #003366; font-weight: bold;">new</span> Color<span style="color: #66cc66;">&#40;</span><span style="color: #CC0000;">255</span>, <span style="color: #CC0000;">0</span>, <span style="color: #CC0000;">0</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #009900; font-style: italic;">// this will fail, since the value is not an instance of Color (instanceof check is used)</span>
balloon.<span style="color: #006600;">color</span> = <span style="color: #3366CC;">&quot;red&quot;</span>;
<span style="color: #009900; font-style: italic;">// this will fail, since we inherit the property definitions from Balloon</span>
balloon.<span style="color: #006600;">diameter</span> = <span style="color: #3366CC;">&quot;small&quot;</span>;</pre></div></div>

<p>We can also use existing classes in method definitions as well. For example, a method definition for a java-bean style setter for color would look like:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">ColoredBalloon.<span style="color: #006600;">methods</span> = <span style="color: #66cc66;">&#123;</span>
  setColor: <span style="color: #66cc66;">&#123;</span>
    parameters:<span style="color: #66cc66;">&#91;</span>Color<span style="color: #66cc66;">&#93;</span>
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>;</pre></div></div>

<p>And all the method definitions are inherited from Balloon (as well as the method implementations through standard JavaScript prototype inheritance).</p>
<h2>Using the Typing Module in Dojo</h2>
<p>This typing capability is available in the <code>dojox.lang.typed</code> module, and can be used just like the standalone &#8220;typed&#8221; function. In addition, this module integrates with Dojo&#8217;s class constructing convenience function, <code>dojo.declare</code>. </p>
<p>One feature that makes the dojox.lang.typed module convenient is that we don&#8217;t need to reassign the return value of typed to the class variable; we can simply do:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">dojo.<span style="color: #006600;">require</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;dojox.lang.typed&quot;</span><span style="color: #66cc66;">&#41;</span>;
dojox.<span style="color: #006600;">lang</span>.<span style="color: #006600;">typed</span><span style="color: #66cc66;">&#40;</span>dojo.<span style="color: #006600;">declare</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;acme.Balloon&quot;</span>, <span style="color: #003366; font-weight: bold;">null</span>, <span style="color: #66cc66;">&#123;</span>
  setVolume: <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>volume<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
  ... <span style="color: #006600;">method</span> implementations
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
acme.<span style="color: #006600;">Balloon</span>.<span style="color: #006600;">properties</span> = <span style="color: #66cc66;">&#123;</span>
  ... <span style="color: #006600;">property</span> definitions  
<span style="color: #66cc66;">&#125;</span>;</pre></div></div>

<p>Furthermore, we can automate the typing of all our classes by setting the Dojo configuration variable <code>dojo.config.typeCheckAllClasses</code> to true before loading <code>dojox.lang.typed</code>. Then all classes that are declared (after <code>dojox.lang.typed</code> is loaded) through <code>dojo.declare</code> will be typed.</p>
<h2>Development/Production Distinction</h2>
<p>The typing module is intended to be used for development, easing the construction of classes that need to work together by verifying invariant assumptions. It is highly recommended that type checking be removed for production code. Type checking adds extra bytes (to download the schemas) and has a performance hit (to perform all the type checks), which should be avoided for production. Fortunately, the unobtrusive design makes this very doable. The actual class implementations are unaffected by typing definitions, and as long as the application runs without any type errors, the application should behave exactly the same without type definitions as it does with them. With this design, type definitions can be stored separately from implementations and easily omitted for production code.</p>
<p>In Dojo, ensuring that typing information is omitted can easily be done with the build process. There are a couple of ways of doing this. First we can utilize the build&#8217;s <code>excludeStart()</code> function to remove typing information. Therefore we could define our Balloon class:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #009900; font-style: italic;">//&gt;&gt;excludeStart(&quot;typed&quot;, true);</span>
dojo.<span style="color: #006600;">config</span>.<span style="color: #006600;">typeCheckAllClasses</span> = <span style="color: #003366; font-weight: bold;">true</span>;
dojo.<span style="color: #006600;">require</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;dojox.lang.typed&quot;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #009900; font-style: italic;">//&gt;&gt;excludeEnd(&quot;typed&quot;);</span>
&nbsp;
dojo.<span style="color: #006600;">declare</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;acme.Balloon&quot;</span>, <span style="color: #003366; font-weight: bold;">null</span>, <span style="color: #66cc66;">&#123;</span>
  setVolume: <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>volume<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
  ... <span style="color: #006600;">method</span> implementations
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #009900; font-style: italic;">//&gt;&gt;excludeStart(&quot;typed&quot;, true);</span>
acme.<span style="color: #006600;">Balloon</span>.<span style="color: #006600;">properties</span> = <span style="color: #66cc66;">&#123;</span>
  ... <span style="color: #006600;">property</span> definitions  
<span style="color: #66cc66;">&#125;</span>;
<span style="color: #009900; font-style: italic;">//&gt;&gt;excludeEnd(&quot;typed&quot;);</span></pre></div></div>

<p>The build process will then strip out all the schema information.</p>
<p>While using <code>excludeStart()</code> is a simple way to exclude type information, it can be a little ugly. Alternately, we could have our schemas stored in separate modules, and then use build profiles to omit the typing modules. This can contribute to better implementation/interface separation.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">acme/Balloon.<span style="color: #006600;">js</span>:
&nbsp;
dojo.<span style="color: #006600;">provide</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;acme.Balloon&quot;</span><span style="color: #66cc66;">&#41;</span>;
dojo.<span style="color: #006600;">require</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;acme.Balloon-schema&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
dojo.<span style="color: #006600;">declare</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;acme.Balloon&quot;</span>, <span style="color: #003366; font-weight: bold;">null</span>, <span style="color: #66cc66;">&#123;</span>
  setVolume: <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>volume<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
  ... <span style="color: #006600;">method</span> implementations
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="javascript">acme/Balloon-schema.<span style="color: #006600;">js</span>:
&nbsp;
dojo.<span style="color: #006600;">provide</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;acme.Balloon-schema&quot;</span><span style="color: #66cc66;">&#41;</span>;
dojo.<span style="color: #006600;">config</span>.<span style="color: #006600;">typeCheckAllClasses</span> = <span style="color: #003366; font-weight: bold;">true</span>;
dojo.<span style="color: #006600;">require</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;dojox.lang.typed&quot;</span><span style="color: #66cc66;">&#41;</span>;
acme.<span style="color: #006600;">Balloon</span>.<span style="color: #006600;">properties</span> = <span style="color: #66cc66;">&#123;</span>
  ... <span style="color: #006600;">property</span> definitions  
<span style="color: #66cc66;">&#125;</span>;</pre></div></div>

<p>Now in the build profile, we can include the schema modules as layerDependencies to completely exclude them from the build:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">dependencies = <span style="color: #66cc66;">&#123;</span>
	layers: <span style="color: #66cc66;">&#91;</span>
		<span style="color: #66cc66;">&#123;</span>
			<span style="color: #000066;">name</span>: <span style="color: #3366CC;">&quot;../acme/Balloon.js&quot;</span>,
			layerDependencies : <span style="color: #66cc66;">&#91;</span>
				<span style="color: #3366CC;">&quot;../acme/Balloon-schema.js&quot;</span>
			<span style="color: #66cc66;">&#93;</span>,
			dependencies: <span style="color: #66cc66;">&#91;</span>
				<span style="color: #3366CC;">&quot;acme.Balloon&quot;</span>
			<span style="color: #66cc66;">&#93;</span>
		<span style="color: #66cc66;">&#125;</span>,
...</pre></div></div>

<h2>Limitations and Potential</h2>
<p>Type checking on property changes can not be performed in IE because this feature relies on JavaScript getters and setters. However (as noted before), this is a development-time tool, and full cross-browser support is not necessary to reap the benefits of type checking. Checking for invalid type assumptions&mdash;and utilizing typing information for integration of components between different developers&mdash;can be achieved during development on a subset of all browsers. Type checked applications will still work on IE; there just won’t be type checks performed on property changes. For production, when full-cross browser support is needed, it is recommended that type checks be eliminated anyway.</p>
<p>The JavaScript-based type checker is also limited in that it can&#8217;t intercept <code>delete</code> operations on properties. When a <code>delete</code> takes place, the setter is not fired, and the type checker is not able to reject the action (in the case of required properties). The type checker also cannot control the addition of new properties that have been declared (in the property definitions or prototype).</p>
<p>JSI-based type checking does not have any mechanism for defining types of local variables. This is intentional. Local variables rarely benefit from type information. Integration of components from different sources can define their interaction solely through public interfaces (which are typeable with JSI), and local type inference mechanisms can usually provide sufficient information about local variable types for IDEs and code analysis.</p>
<p>A more complete JSI-based type checking system can be seen in <a href="http://www.persvr.org/">Persevere</a>. Persevere implements JSI for type checking in the server-side JavaScript environment, and is able to reject delete and new property actions that do not conform to the schema. Typing in JavaScript has been a controversial idea due to the obtrusive nature of traditional typing annotations, but JSI allows gradual type constraints to be applied in a way that does not interfere with JavaScript&#8217;s simple syntax and object model.</p>
<p>This typing scheme has also been proposed to the ECMAScript working group. As noted before, the typing system proposed for edition 4 required extensive new syntax and relied significantly on namespaces, which have been rejected. A schema-based typing system is perhaps the most reasonable alternative for adding typing capabilities to ECMAScript, and provides significant benefits over the more static type systems that quash the interactive, dynamic nature of JavaScript. With the more gradual approach that is being taken to evolve the language, this typing system provides the perfect mechanism for preserving the familiar syntax and meta-programming abilities that exemplify JavaScript.</p>
<h2>Portability and Metadata Retrieval</h2>
<p>JSON schema interfaces are completely language-agnostic. This means that interfaces can be defined that apply to implementations in different languages. This can be particular useful for defining contracts in RPC-style situations. In fact, the <a href="http://groups.google.com/group/json-schema/web/service-mapping-description-proposal">SMD format</a>, which is used extensively by Dojo for defining <a href="http://www.sitepen.com/blog/2008/03/19/pluggable-web-services-with-smd/">remote services</a>, is essentially a remote service-oriented form of JSI.</p>
<p>One of the challenges with traditional class systems is finding a way to reify type information. This is a non-issue with JSI, since the type system is based completely on a runtime data structure that is readily available and already understood.</p>
<h2>Typing in JavaScript</h2>
<p>While there has been a lot of controversy over typing, only the most extreme would not be willing to concede that in certain situations, typing can be a valuable asset for defining contracts between components. JSI allows for more robust evolution of an application, faster detection of invariant violations that lead to hard-to-find bugs, and better information for integration of components and type-based tooling. Furthermore, leveraging JSON schema gives developers a very rich set of options for constraining values, much more than most type systems.</p>
<p>JSI gives us a standardized data structure for defining types&mdash;allowing for more robust large-scale application development, a better pathway for JavaScript tool evolution, clean implementation/interface separation, and an integrated, intuitive class/typing system.  And it&#8217;s available in both the Dojo Toolkit and Persevere today!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2009/06/23/unobtrusive-javascript-typing-via-json-schema-interfaces/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Using REST Channels with cometD</title>
		<link>http://www.sitepen.com/blog/2009/06/15/using-rest-channels-with-cometd/</link>
		<comments>http://www.sitepen.com/blog/2009/06/15/using-rest-channels-with-cometd/#comments</comments>
		<pubDate>Mon, 15 Jun 2009 08:02:43 +0000</pubDate>
		<dc:creator>Kris Zyp</dc:creator>
		
		<category><![CDATA[Bayeux]]></category>

		<category><![CDATA[Cometd]]></category>

		<category><![CDATA[Dojo]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/2009/06/15/using-rest-channels-with-cometd/</guid>
		<description><![CDATA[REST Channels provides a mechanism for receiving notifications of data changes and integrates Comet-style asynchronous server sent messages with a RESTful data-oriented architecture. Dojo includes a REST Channels client module which integrates completely with Dojo&#8217;s JsonRestStore, allowing messages to be delivered through the Dojo Data API seamlessly to consuming widgets, with minimal effort. The REST [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://cometdaily.com/2008/09/02/rest-channels-http-channels-with-json-support/">REST Channels</a> provides a mechanism for receiving notifications of data changes and integrates Comet-style asynchronous server sent messages with a RESTful data-oriented architecture. <a href="http://cometdaily.com/2008/11/12/using-rest-channels-in-dojo/">Dojo includes a REST Channels client module</a> which integrates completely with <a href="http://dojotoolkit.org/">Dojo&#8217;s</a> <a href="http://docs.dojocampus.org/dojox/data/JsonRestStore">JsonRestStore</a>, allowing messages to be delivered through the Dojo Data API seamlessly to consuming widgets, with minimal effort. The REST Channels module will automatically connect to a REST Channels server, like <a href="http://www.persvr.org/">Persevere</a> (which offers REST Channels out of the box). However, existing infrastructure may necessitate the use of an alternate Comet server like <a href="http://docs.codehaus.org/display/JETTY/Cometd+(aka+Bayeux)">Jetty&#8217;s cometD</a> server. REST Channels can be used on top of another Comet protocol like <a href="http://svn.xantus.org/shortbus/trunk/bayeux/bayeux.html">Bayeux&#8217;s</a> long-polling protocol and with a little bit of reconfiguration, you can use Dojo&#8217;s REST Channels with a cometD server to achieve Comet-REST integration.</p>
<h2>Receiving Data Notifications</h2>
<p>REST Channels is designed to unite the concept of topics with resource locators. Therefore, REST Channels can leverage Bayeux&#8217;s topic names to indicate the resource that is being targeted. We can then subscribe to Bayeux&#8217;s channels and then delegate all the data notification messages to the restListener which will delegate the proper data events through the data stores:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #009900; font-style: italic;">// first initialize cometD</span>
dojo.<span style="color: #006600;">require</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;dojox.cometd&quot;</span><span style="color: #66cc66;">&#41;</span>;
dojo.<span style="color: #006600;">require</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;dojox.cometd.RestChannels&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
dojox.<span style="color: #006600;">cometd</span>.<span style="color: #006600;">init</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;/cometd&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
dojo.<span style="color: #006600;">subscribe</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;/cometd/**&quot;</span>, <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>msg<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
   dojox.<span style="color: #006600;">data</span>.<span style="color: #006600;">restListener</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span>
      channel: msg.<span style="color: #006600;">channel</span>,
      event: msg.<span style="color: #006600;">data</span>.<span style="color: #006600;">event</span>,
      result: msg.<span style="color: #006600;">data</span>.<span style="color: #006600;">result</span>
   <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>This could be used in conjunction with a JsonRestStore, and messages would be delegated to the store&#8217;s events:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">weatherStore = <span style="color: #003366; font-weight: bold;">new</span> dojox.<span style="color: #006600;">data</span>.<span style="color: #006600;">JsonRestStore</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span>target:<span style="color: #3366CC;">&quot;/weather/&quot;</span><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>Now it is possible to publish data change notification messages such that clients will receive and interpret the messages properly. To publish a data notification message on Jetty&#8217;s cometD hub, we can call the <code>doPublish</code> with something like:</p>

<div class="wp_syntax"><div class="code"><pre class="java">bayeux.<span style="color: #006600;">doPublish</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;/weather/lax&quot;</span>, <span style="color: #000000; font-weight: bold;">null</span>, laxWeatherUpdate, <span style="color: #000000; font-weight: bold;">null</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>Which should produce a Bayeux notification message like:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #66cc66;">&#123;</span>
  <span style="color: #3366CC;">&quot;channel&quot;</span>: <span style="color: #3366CC;">&quot;/weather/lax&quot;</span>,
  <span style="color: #3366CC;">&quot;clientId&quot;</span>: <span style="color: #3366CC;">&quot;23ab8a887baaa&quot;</span>,
  <span style="color: #3366CC;">&quot;data&quot;</span>: <span style="color: #66cc66;">&#123;</span>
     <span style="color: #3366CC;">&quot;event&quot;</span>:<span style="color: #3366CC;">&quot;PUT&quot;</span>,
     <span style="color: #3366CC;">&quot;result&quot;</span>:<span style="color: #66cc66;">&#123;</span>
       <span style="color: #3366CC;">&quot;low&quot;</span>: <span style="color: #CC0000;">65</span>,
       <span style="color: #3366CC;">&quot;high&quot;</span>: <span style="color: #CC0000;">78</span>,
       <span style="color: #3366CC;">&quot;skies&quot;</span>: <span style="color: #3366CC;">&quot;clear&quot;</span>
    <span style="color: #66cc66;">&#125;</span>
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Now this message will be routed through the restListener and onSet events will be fired for any attributes that were updated in the local cache of the &#8220;/weather/lax&#8221; item. If the <i>lax</i> item was being displayed in a data-aware widget, it will automatically be updated. For example, the DataGrid supports data notification events, and if this item appears in a DataGrid, the corresponding row will automatically display the new value.</p>
<h2>Subscribing to Resources</h2>
<p>One of the key integration points that REST Channels provides between data access and notification routing is in auto-subscribing to resources when they are retrieved. The primary use case for REST Channels is in providing a real-time view of data, and therefore when data is retrieved from the server, REST Channels can automatically subscribe to the resource to receive all future notifications of changes to the object. With a true REST Channels implementation, subscription information is included in GET requests, so that a single request can be made to a server that both requests a resource and subscribes to it at the same time. If you are just using a cometD server, such an integration is not automatic. There are a couple of different approaches for subscribing to resources.</p>
<p>On the client-side, we can send subscription requests when we make GET requests. This can be done by intercepting the REST GET request handler, and creating subscriptions.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">dojo.<span style="color: #006600;">connect</span><span style="color: #66cc66;">&#40;</span>dojo, <span style="color: #3366CC;">&quot;xhrGet&quot;</span>, <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>args<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
  dojox.<span style="color: #006600;">cometd</span>.<span style="color: #006600;">subscribe</span><span style="color: #66cc66;">&#40;</span>args.<span style="color: #006600;">url</span>, <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
    <span style="color: #009900; font-style: italic;">// nothing needed, handled by the catch-all subscription</span>
  <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>All GET requests will then trigger a subscription automatically. One could easily add some conditional logic that only subscribes on a subset of requests.</p>
<p>The biggest disadvantage of client generated subscription requests is that they generate two requests for each resource access, one GET and one subscription request (as a POST). If the REST handler for a server can be modified to understand the subscription header that REST Channels adds to GET requests, the server can subscribe the client without requiring additional requests. The key to making this work, is to be able to connect cometD&#8217;s client connections with the request handler. One way to do this is to define a Bayeux handler that will put the current client object in the HTTP session, and then retrieve it from the session in the REST handler. The REST handler can then subscribe the client to the resource locator topic.</p>
<p>One tricky aspect of this approach is that it is possible for multiple client connections to exist in a single session. Each page will have its own cometD client connection, but will be in the same HTTP session. Therefore, the client connections need to be stored and accessed by their client id. In order for the REST handler to determine the correct client id for a client, you can have the Client-Id header set on the  requests, and then this id can be used to find the correct Bayeux client connection. RestChannels automatically sets the Client-Id header, but the correct client id from the cometD handler must be assigned to the RestChannels clientId variable:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">dojox.<span style="color: #006600;">cometd</span>.<span style="color: #006600;">init</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;/cometd&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">addCallback</span><span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
  dojox.<span style="color: #006600;">rpc</span>.<span style="color: #006600;">Client</span>.<span style="color: #006600;">clientId</span> = dojox.<span style="color: #006600;">cometd</span>.<span style="color: #006600;">clientId</span>;
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>Together these techniques can be used to combine a REST architecture with a cometD server for data notifications with Dojo&#8217;s REST capabilities in JsonRestStore, and complete integration into Dojo&#8217;s data event notification system.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2009/06/15/using-rest-channels-with-cometd/feed/</wfw:commentRss>
		</item>
		<item>
		<title>JavaScriptDB: Persevere&#8217;s New High-Performance Storage Engine</title>
		<link>http://www.sitepen.com/blog/2009/04/20/javascriptdb-perseveres-new-high-performance-storage-engine/</link>
		<comments>http://www.sitepen.com/blog/2009/04/20/javascriptdb-perseveres-new-high-performance-storage-engine/#comments</comments>
		<pubDate>Tue, 21 Apr 2009 03:47:44 +0000</pubDate>
		<dc:creator>Kris Zyp</dc:creator>
		
		<category><![CDATA[Persevere]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/2009/04/20/javascriptdb-perseveres-new-high-performance-storage-engine/</guid>
		<description><![CDATA[The latest beta of Persevere features a new native object storage engine called JavaScriptDB that provides high-end scalability and performance. Persevere now outperforms the common PHP and MySQL combination for accessing data via HTTP by about 40% and outperforms CouchDB by 249%. The new storage engine is designed and optimized specifically for persisting JavaScript and [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://code.google.com/p/persevere-framework/">latest beta</a> of <a href="http://www.persvr.org/">Persevere</a> features a new native object storage engine called JavaScriptDB that provides high-end scalability and performance. Persevere now outperforms the common PHP and MySQL combination for accessing data via HTTP by about 40% and outperforms CouchDB by 249%. The new storage engine is designed and optimized specifically for persisting JavaScript and JSON data with dynamic object structures. It is also built for extreme scalability, with support for up to 9,000 petabytes of JSON/JS data in addition to any binary data.<br />
<img src='http://www.sitepen.com/blog/wp-content/uploads/2009/04/fast-commit.png' alt='fast-commit.png' /></p>
<p>These statistics are even more impressive when one considers all the additional functionality that Persevere provides while outperforming these other storage systems. MySQL utilizes traditional fixed structure schemas requiring homogenous records in a table, while JavaScriptDB (as well as CouchDB) support storage of heterogeneous objects of any structure in tables. Persevere/JavaScriptDB goes further with the flexibility to <a href="http://www.sitepen.com/blog/2008/11/17/evolving-schemas-with-persevere/">evolve schemas</a> and handle partial schemas. Persevere also provides integrated <a href="http://www.sitepen.com/blog/2008/11/02/using-the-persistent-object-model-in-persevere/">server side JavaScript (SSJS) with persistence</a>, Comet-driven data change notifications, <a href="http://www.sitepen.com/blog/2008/11/02/using-the-persistent-object-model-in-persevere/">JSONQuery</a>, <a href="http://docs.persvr.org/documentation/jsonquery">standards based HTTP interface with content negotiation</a>, <a href="http://docs.persvr.org/documentation/json-rpc">JSON-RPC interface to SSJS</a>, cross-domain handling, <a href="http://docs.persvr.org/documentation/json-rpc">CSRF protection</a>, and more. All of these things are additional features that one would have to add to the stack for other storage systems, making them even slower. Persevere includes this functionality out of the box, while still maintaining extremely fast performance.</p>
<h3>Test Scenario</h3>
<p>These tests were performed on a Mac/OS-X with a 2GHz dual-core Intel processor and 1 GB 667 MHz DDR2 memory. The PHP/Apache/MySQL setup used <a href="http://www.mamp.info/en/documentation/index.html">MAMP</a> 1.7.2 which includes PHP 5.2.6, MySQL 5.0.41, and Apache 2.0.59. The CouchDB tests were performed with CouchDBX version 0.8 (which uses CouchDB 0.8.1). Persevere&#8217;s nightly builds from late March were used for JavaScriptDB tests. </p>
<p>Three different operations were performed in the tests:</p>
<ul>
<li>Insert/POST operation to create a new object</li>
<li>Update/PUT operation to update an object</li>
<li>Query/GET to search for objects by an (indexed) field/property</li>
</ul>
<p>On the PHP/MySQL tests, all operations were handled by a very simple PHP script that first did a quick security check query against a small table (actually empty for the tests) to emulate the security capabilities of Persevere and CouchDB (although CouchDB&#8217;s security capabilities are limited, and probably often require additional logic), and then the main query was executed against MySQL, whether it be an INSERT, UPDATE, or SELECT. All the created objects/records had four properties/fields for all three systems. In MySQL, two properties were indexed, one being the primary key, the other being the property that was queried on in the query requests. In CouchDB, a simple view was created that indexed on a single property. This view was used for the requests that queried by index. Both Persevere and CouchDB tests used their standard HTTP interface for creating, updating, and querying. </p>
<p>Tests were carried out by a HTTP client running on 10 threads concurrently issuing a sequence of 200 of each type of request. The &#8220;full test&#8221; performed create, update, and query requests. The &#8220;write test&#8221; performed create and update requests, and the &#8220;read test&#8221; only performed query requests. The files used to perform the benchmarks are available <a href="http://www.sitepen.com/labs/code/persevere/perf.zip">here</a>.<br />
<img src='http://www.sitepen.com/blog/wp-content/uploads/2009/04/high-integrity-commit.png' alt='high-integrity-commit.png' /></p>
<h2>Test Conclusions</h2>
<p>Two sets of tests were run&mdash;one that used fast commits that do not wait for committed data to be actually physically written to the disk (allowing for normal OS write-back caching), and high-integrity commits which cause the committed data to be forced to the disk. JavaScriptDB has a <a href="http://docs.persvr.org/documentation/storage-model#TOC-JavaScriptDB">setting</a> for choosing which style of commits to use. In MySQL, the MyISAM storage engine was used for fast commits, and the InnoDB storage engine was used for high-integrity commits. CouchDB always uses high-integrity commits.</p>
<p>While PHP is not the fastest language, the script that was used for these tests was very trivial, and it&#8217;s unlikely that PHP code execution significantly detracted from the overall performance of the PHP/MySQL combination. With this simple, streamlined PHP script, a very fast classic setup was used. Alternate languages would not be likely to improve the performance by very much. Yet, Persevere&#8217;s JavaScriptDB still beat this setup by a significant margin. With more complex request handlers that might provide more of the functionality that Persevere already provides, the margin would be likely to increase even more. Quite simply, the classic application server + MySQL database setup is hard-pressed to compete with Persevere in terms of performance for most normal database interactions.</p>
<p>So how does Persevere achieve this level of performance with the JavaScriptDB storage? The dynamic object-oriented nature of the data that is stored in JavaScriptDB is much different than that of a traditional relational database, so a number of innovative approaches were employed.</p>
<h2>Direct Data-Bound Object Representation</h2>
<p>One of the central concepts of Persevere is that all persisted data is mapped to JavaScript objects. This enables server side JavaScript functions and handlers to easily be able to interact with persisted data, and provides a convenient in-memory representation of data that allows for intuitive normal object-oriented data interaction. However, in Persevere this more than just a convenient API&mdash;it also facilitates efficient memory utilization by providing a single in-memory representation that can be reused at multiple levels.</p>
<p>In a traditional application stack, a record must have separate in-memory representations for each different level in the stack. A database may have an in-memory representation before serializing result sets back to the application. The application may have result set level representation, which then might be mapped to an object representation. Every one of these levels consumes more memory. These extra layers increase latency and overhead as well. In addition, most database driven applications rely on TCP/IP communication with the database, which consumes a large amount of resources as well. With the JavaScriptDB, the single in-memory object is efficiently reused at the database level for all result sets and data caching. This not only means less memory-consumption, but it also translates to more efficient CPU cache utilization for Persevere, and direct low-latency access to data.</p>
<h3>Shared Cache of Objects with Copy-on-Write</h3>
<p>Not only are in-memory objects shared between the application level and the database level, but Persevere also utilizes a shared cache of objects between threads to ensure that any given record/object only exists in memory at most one time. Traditional application frameworks process separate HTTP requests concurrently and each request will have its own result set and a copy of data. These can lead to significant duplication of data in memory. With Persevere, objects are always reused if they are still available in memory. </p>
<p>While this technique is relatively simple for read-only data, Persevere still maintains virtual memory isolation between threads to protect against concurrent access between threads and ensuing race conditions. Persevere does this by performing copy-on-write style values in objects. When a property is modified, internally its value is modified to being a &#8220;transactional&#8221; value that actually has multiple states depending on which thread is accessing the objects. Therefore an object can be modified by one thread, but another thread can access the same object without seeing the uncommitted change. Property changes are made visible when transactions are committed. This technique allows Persevere to maintain transactional isolation between concurrent request handlers, while minimizing the record/objects that must be held in memory. Persevere&#8217;s architecture combined with JavaScriptDB&#8217;s integration minimizes memory consumption, allowing internal caches to be maximized for optimal performance.</p>
<p>Persevere utilizes the sophisticated least recently used (LRU) caching capabilities of the Java Virtual Machines&#8217;s (JVM) soft referencing mechanism. In-memory objects, as well as JavaScriptDB&#8217;s indices, are cached via soft reference tables. This allows the JVM to utilize an integrated view of reachability and object access timestamps to determine which objects to collect and discard. This means that objects that are reachable by currently executing code will always stay in the cache (since they must stay in memory due to reachability) as long as they are reachable. Unreachable objects are then discarded according to LRU strategies. Since the JVM&#8217;s garbage collection handles object collection at a global level, it is also able to optimally select objects for collection without being constrained by module level view. This means that if the indices are not being used frequently, more memory can be allocated to the object cache and vice versa. Caches are maintained according to usage and reachability with the JVM&#8217;s global perspective for optimal discarding strategy.</p>
<h2>Append-based Database Storage</h2>
<p>JavaScriptDB uses an append-based database format to store data. Many traditional database will synchronously commit data to a transaction log file before committing data to the main storage table, which requires multiple writes. On the other hand, JavaScriptDB appends transactional data directly to the main storage file such that writes can be committed with a single IO operation. This also enables JavaScriptDB to efficiently maintain a version history of the database and its records. The storage file is essentially a running log of transactions, and these transactions are exposed as the Transaction table. By storing data as a sequential set of transaction, JavaScriptDB not only can persist data quickly, it also provides efficient access to the transactions that have taken place and a version history of the database and objects within it.</p>
<h2>Adaptive On-Demand Concurrent Indexing</h2>
<p>JavaScriptDB features a dynamic approach to indexing that minimizes the configuration and management required to create and maintain tables, and maximizes performance. By default, JavaScriptDB indexes all properties of persisted objects, so typical queries can almost always be run in fast O(log n) time. However, the indexer does not block write operations to complete index updates when objects are added, deleted, or modified. Rather, the indexer execution takes place concurrently in a background asynchronous task executing threads. As objects are indexed, the index update operations are delegated to the appropriate index nodes, which are also executed as asynchronous tasks. When an index is needed for a query, any outstanding updates along the node tree path are completed so the query can execute.</p>
<p>It is worth noting that this on-demand indexing does not mean that the entire index must be updated to execute a query. Often (and usually in the case of large databases) an object may be updated that affects an index node that isn&#8217;t used in a subsequent query. In this case, the query can still execute without waiting for the index node to be updated. JavaScriptDB properly orchestrates concurrent indexing such that nodes are updated through lower-priority background threads when possible, and immediately updated on-demand as necessary. This allows write operations to take place very quickly, while still allowing indexes to be ready for fast query operations as well. This also allows Persevere to utilize resources and CPU processing more evenly and smoothly. Background processes can take CPU time as needed when client requests are not demanding immediate data retrieval.<br />
<img src='http://www.sitepen.com/blog/wp-content/uploads/2009/04/indextreejavascriptdb.png' alt='indextreejavascriptdb.png' style="float:right"/></p>
<p>Furthermore, JavaScriptDB uses adaptive techniques with indexing. If a particular index has been unused for some time while many objects have been added to a table with the corresponding property, JavaScriptDB will stop proactively updating the index to conserve resources. When an index is no longer proactively updated, the index will only be updated on-demand, when a query is performed that requires that index. Once the index is updated, it will resume proactive updates (at least until disuse causes it to go back to a non-proactive update state). This approach allows JavaScriptDB to automatically do appropriate and efficient indexing with minimal manual configuration. JavaScriptDB does also support <a href="http://docs.persvr.org/documentation/storage-model#TOC-JavaScriptDB">manual configuration of indexes</a>, for situations where you may want explicit control of indexing.</p>
<h2>Batched writes in integrity mode</h2>
<p>One of the most expensive operations that a database can perform is a forced synchronous disk write operation. These operations are necessary for high-integrity commit mode where the commit does not return until the database is certain that the data has actually been written to the disk, fulfilling the durability component of <a href="http://en.wikipedia.org/wiki/ACID">ACID</a> compliance. These operations can take around 10ms. In order to improve the performance of high-integrity commits, Persevere will detect when multiple writes are taking place concurrently and batch multiple writes together in a single synchronous disk write operation. When a number of concurrent write requests are being sent to Persevere, this can significantly reduce the number of synchronous writes that must take place and greatly improve performance.</p>
<h2>Pluggable Storage</h2>
<p><img src='http://www.sitepen.com/blog/wp-content/uploads/2009/04/perseverejavascriptdb.png' alt='perseverejavascriptdb.png'  style="float:right" /><br />
Persevere uses a pluggable storage system. JavaScriptDB is one of several data source plugins (the default data source) that can be used with Persevere. Persevere supports heterogeneous storage configurations. This means you can leverage the performance and flexibility of JavaScriptDB in Persevere without abandoning existing relational databases, as well as other data sources. Even custom data sources can be created for unique storage systems.</p>
<p>The <a href="http://groups.google.com/group/serverjs">ServerJS working group</a> is also <a href="http://groups.google.com/group/serverjs/browse_thread/thread/3a85696ab6552410#">considering</a> a standard API for database interaction that might possibly allow JavaScriptDB to be used as a standalone database engine for use by other Rhino-based frameworks like <a href="http://www.helma.org/">Helma</a> (of course Persevere + JavaScriptDB can already be used with existing JavaScript modules, and it can be used as a database for Java applications through it&#8217;s Java API).</p>
<h2>Future Improvements</h2>
<p>This is the first release of JavaScriptDB, so there is still significant opportunities for continuing to improve and refine this storage engine. Currently, JavaScriptDB does not utilize indices for nested object queries (the equivalent of inner joins in relational DBs). Consequently queries of the form [?prop1=&#8217;something&#8217;] will execute in <code>O(log n)</code> time, but queries of the form <code>[?prop1.prop2='something']</code> will only execute in <code>O(n)</code>. Future versions will provide fast <code>O(log n)</code> for a much broader range of queries. A later release will also provide true ACID compliance (the current version does not fulfill the atomicity constraint). Finally, replication/clustering services will be added in the future as well, for distributing Persevere workload across multiple servers.</p>
<h2>Real Value</h2>
<p>As Alex Payne <a href="http://al3x.net/2008/12/04/recession-engineering.html">pointed out</a>, the economy may be ending the era of disregard for system performance and efficiency with the excuse of buying more servers. More servers costs more money, and architectures like Persevere that can efficiently handle large numbers of users and traffic with minimal hardware resources equates to real money saved.</p>
<p>Persevere combines numerous advanced capabilities for web-accessible data including standards-based HTTP interface, JSONQuery, JSON-RPC, server side JavaScript, Comet-based data notifications, robust security, and more. Now these capabilities are available with speed and scalability that outperforms the most common web application systems, allowing you to build high-performance <a href="http://www.sitepen.com/blog/2008/07/18/clientserver-model-on-the-web/">client/server Ajax web applications</a> with unprecedented ease, efficiency, and value.</p>
<p><b>Update</b>: Jan Lehnardt pointed out that CouchDB is now at version 0.9.0 and OS-X is not the optimal platform for CouchDB, so the latest version CouchDB can presumably improve upon the CouchDB performance shown in these tests. Hopefully we can progress towards better benchmarking tools for this new breed of databases.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2009/04/20/javascriptdb-perseveres-new-high-performance-storage-engine/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Queued: Drag and Drop in the Queue</title>
		<link>http://www.sitepen.com/blog/2009/04/16/queued-drag-and-drop-in-the-queue/</link>
		<comments>http://www.sitepen.com/blog/2009/04/16/queued-drag-and-drop-in-the-queue/#comments</comments>
		<pubDate>Thu, 16 Apr 2009 16:52:47 +0000</pubDate>
		<dc:creator>Bryan Forbes</dc:creator>
		
		<category><![CDATA[Dojo]]></category>

		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[air]]></category>

		<category><![CDATA[queued]]></category>

		<category><![CDATA[dnd]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/2009/04/16/queued-drag-and-drop-in-the-queue/</guid>
		<description><![CDATA[During the interaction design phase, we determined that Netflix&#8217;s current drag and drop reordering feature was well thought out &#8212; so we set out to create the same reordering behavior in Queued.  As Revin mentioned before, we also wanted to keep Queued as light as possible; because of this, we decided early on to [...]]]></description>
			<content:encoded><![CDATA[<p>During the <a href="http://www.sitepen.com/blog/2009/03/25/queued-new-interaction-tricks-for-the-old-netflix-dog/">interaction design phase</a>, we determined that Netflix&#8217;s current drag and drop reordering feature was well thought out &mdash; so we set out to create the same reordering behavior in Queued.  As <a href="http://www.sitepen.com/blog/2009/03/30/architecting-queued/">Revin mentioned before</a>, we also wanted to keep Queued as light as possible; because of this, we decided early on to not use any of the Dijit infrastructure to create the queue listings.  Not only that, but the Dojo Grid would not work for the queues because it doesn&#8217;t support drag and drop reordering of rows.  This meant we would have to come up with something which would be flexible (yet fast) to render the queue.</p>
<p>In the user interface design phase, we decided that each of the lists in the &#8220;Your Queue&#8221; section would be based on HTML tables.  In Queued, only the DVD queue and the Instant list can be reordered, so we&#8217;ll focus on the DVD queue.</p>
<p>Here&#8217;s the HTML for the DVD queue:</p>

<div class="wp_syntax"><div class="code"><pre class="html4strict"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;table</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;queueList&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;thead&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tr</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;listQueuedHead&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;th</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;index&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Movie<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/th&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;th</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;top&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/th&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;th</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;title&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/th&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;th</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;instant&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Instant<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/th&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;th</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;stars&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Star Rating<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/th&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;th</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;genre&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Genre<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/th&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;th</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;format&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Disc Format<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/th&gt;</span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;th</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;remove&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Remove<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/th&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tr&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;</span>/thead&gt;</span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tbody</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;queueTemplateNode&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;listQueuedBody&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tbody&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/table&gt;</span></span></pre></div></div>

<p>This table&#8217;s body corresponds to a <code>queueList</code> object:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">qd.<span style="color: #006600;">app</span>.<span style="color: #006600;">queueList</span> = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
	<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">list</span> = <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>;
	<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">domNode</span> = <span style="color: #003366; font-weight: bold;">null</span>;
	<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">constructor</span> = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>options<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
		dojo.<span style="color: #006600;">mixin</span><span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>, options<span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">domNode</span> = dojo.<span style="color: #006600;">byId</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;queueTemplateNode&quot;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">dndSource</span> = <span style="color: #003366; font-weight: bold;">new</span> dojo.<span style="color: #006600;">dnd</span>.<span style="color: #006600;">Source</span><span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">domNode</span>, <span style="color: #66cc66;">&#123;</span>
			accept: <span style="color: #3366CC;">&quot;movie&quot;</span>,
			skipForm: <span style="color: #003366; font-weight: bold;">true</span>,
			withHandles: <span style="color: #003366; font-weight: bold;">true</span>,
			isSource: <span style="color: #003366; font-weight: bold;">true</span>,
			singular: <span style="color: #003366; font-weight: bold;">true</span>,
			creator: dojo.<span style="color: #006600;">hitch</span><span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>, <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">createItem</span><span style="color: #66cc66;">&#41;</span>
		<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">dndSource</span>.<span style="color: #006600;">insertNodes</span><span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">false</span>,
			dojo.<span style="color: #006600;">filter</span><span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">result</span>.<span style="color: #006600;">items</span>, <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>i<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
				<span style="color: #009900; font-style: italic;">// in English: for &quot;queue&quot; and &quot;instant&quot;,</span>
				<span style="color: #009900; font-style: italic;">// skip when position==null</span>
				<span style="color: #000066; font-weight: bold;">return</span> i.<span style="color: #006600;">position</span> ||
					<span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">type</span>!=<span style="color: #3366CC;">&quot;queue&quot;</span> &amp;&amp; <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">type</span>!=<span style="color: #3366CC;">&quot;instant&quot;</span><span style="color: #66cc66;">&#41;</span>;
			<span style="color: #66cc66;">&#125;</span>, <span style="color: #000066; font-weight: bold;">this</span><span style="color: #66cc66;">&#41;</span>
		<span style="color: #66cc66;">&#41;</span>;
		dojo.<span style="color: #006600;">connect</span><span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">dndSource</span>, <span style="color: #3366CC;">&quot;onDropInternal&quot;</span>, <span style="color: #000066; font-weight: bold;">this</span>, <span style="color: #3366CC;">&quot;onDrop&quot;</span><span style="color: #66cc66;">&#41;</span>;
		dojo.<span style="color: #006600;">connect</span><span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">dndSource</span>, <span style="color: #3366CC;">&quot;onDndCancel&quot;</span>, <span style="color: #000066; font-weight: bold;">this</span>, <span style="color: #3366CC;">&quot;onDragCancel&quot;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>;
<span style="color: #66cc66;">&#125;</span>;</pre></div></div>

<p>When the <code>queueList</code> is instantiated, a <code>dojo.dnd.Source</code> object is created; this means the body of the table is now a source for items to be dragged out of.  This particular source also functions as a container &mdash; items can be dropped on it &mdash; and will only accept items with a type of &#8220;movie&#8221; (meaning that all other items will be ignored).  We then populate the queue when <code>insertNodes</code> is called with the filtered list of items we want to add.  The <code>insertNodes</code> function calls the <code>creator</code> parameter to <code>dojo.dnd.Source</code>.  Let&#8217;s take a look at what that function does:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">createItem</span> = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span>, hint<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
	<span style="color: #000066; font-weight: bold;">if</span><span style="color: #66cc66;">&#40;</span>hint == <span style="color: #3366CC;">&quot;avatar&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
		<span style="color: #003366; font-weight: bold;">var</span> node = dojo.<span style="color: #006600;">doc</span>.<span style="color: #006600;">createElement</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;div&quot;</span><span style="color: #66cc66;">&#41;</span>;
		node.<span style="color: #006600;">className</span> = <span style="color: #3366CC;">&quot;movieDragAvatar&quot;</span>;
		node.<span style="color: #006600;">innerHTML</span> = <span style="color: #000066; font-weight: bold;">item</span>.<span style="color: #000066; font-weight: bold;">item</span>.<span style="color: #006600;">title</span>.<span style="color: #006600;">title</span>;
		<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">draggingitem</span> = <span style="color: #000066; font-weight: bold;">item</span>;
		<span style="color: #000066; font-weight: bold;">return</span> <span style="color: #66cc66;">&#123;</span>
			node: node,
			data: <span style="color: #000066; font-weight: bold;">item</span>,
			type: <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">type</span>
		<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>
	<span style="color: #003366; font-weight: bold;">var</span> listItem = <span style="color: #003366; font-weight: bold;">new</span> qd.<span style="color: #006600;">app</span>.<span style="color: #006600;">queueItem</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span>
			<span style="color: #000066; font-weight: bold;">item</span>: <span style="color: #000066; font-weight: bold;">item</span>,
			type: <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">type</span>,
			parent: <span style="color: #000066; font-weight: bold;">this</span>
		<span style="color: #66cc66;">&#125;</span>, <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">domNode</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #000066; font-weight: bold;">return</span> <span style="color: #66cc66;">&#123;</span>
		node: listItem.<span style="color: #006600;">domNode</span>,
		data: listItem,
		type: <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">type</span>
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>;</pre></div></div>

<p>As you can see, <code>createItem</code> gets called in a couple of situations.  We mentioned <code>insertNodes</code>, but it is also called when you drop an item onto a source and when you start a drag.  The latter situation calls the creator with the <code>hint</code> argument set to <code>"avatar"</code>.  In that situation, we return a node that has a simple representation of what we are dragging that follows the mouse.  When <code>insertNodes</code> calls <code>createItem</code>, it will instantiate a <code>qd.app.queueItem</code> which handles creating the correct markup for a row in the table.  Then, <code>insertNodes</code> adds the <code>node</code> property of the returned object to the node passed to the <code>dojo.dnd.Source</code> constructor.  You might be wondering what a <code>qd.app.queueItem</code> does in its constructor; it simply takes the information provided in the item and constructs a table row.</p>
<p>The <code>dojo.dnd.Source</code> object also provides some events to which we can connect.  The first, <code>onDropInternal</code>, is triggered when the user drops an item dragged from the DVD Queue into the DVD Queue &mdash; in other words, a re-order of the queue.  The event handler, <code>onDrop</code>, looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">onDrop</span> = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>nodes<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
	<span style="color: #003366; font-weight: bold;">var</span> node = nodes<span style="color: #66cc66;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #66cc66;">&#93;</span>;
	<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">dndSource</span>.<span style="color: #006600;">getAllNodes</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">forEach</span><span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>n, i<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
		<span style="color: #003366; font-weight: bold;">var</span> listItem = <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">dndSource</span>.<span style="color: #006600;">getItem</span><span style="color: #66cc66;">&#40;</span>n.<span style="color: #006600;">id</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">data</span>;
		<span style="color: #000066; font-weight: bold;">if</span><span style="color: #66cc66;">&#40;</span>n.<span style="color: #006600;">id</span> == node.<span style="color: #006600;">id</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
			<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">reorder</span><span style="color: #66cc66;">&#40;</span>listItem, i<span style="color: #CC0000;">+1</span>, <span style="color: #003366; font-weight: bold;">false</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>, <span style="color: #000066; font-weight: bold;">this</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">draggingitem</span> = <span style="color: #003366; font-weight: bold;">null</span>;
<span style="color: #66cc66;">&#125;</span>;</pre></div></div>

<p>The <code>reorder</code> method handles talking to Netflix&#8217;s service to move items around and it also renumbers the rows in the HTML table.  The second interesting event (to us) is <code>onDndCancel</code>.  It is triggered when a drag operation is canceled &mdash; for example, when the user hits ESC during a drag.  It is also triggered at the end of any drop.  Our event handler, <code>onDragCancel</code>, cleans up after our drag operations:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">onDragCancel</span> = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
	<span style="color: #000066; font-weight: bold;">if</span><span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">draggingitem</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
		<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">draggingitem</span> = <span style="color: #003366; font-weight: bold;">null</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>;</pre></div></div>

<p>In the end, that&#8217;s all it took to get drag and drop working in Queued.  Dojo&#8217;s drag and drop API is a robust, flexible system which can be easily tailored to your application by passing a creator function to a <code>dojo.dnd.Source</code>.  All the creator function has to do is know how to create a representation of the item to be appended to the source (in this case, a row appended to a table) and create a representation of the item while it&#8217;s being dragged.  After you&#8217;ve set that up, you just have to listen to the source&#8217;s events and make adjustments on the server-side accordingly.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2009/04/16/queued-drag-and-drop-in-the-queue/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Queued and AIR Issues, Part II</title>
		<link>http://www.sitepen.com/blog/2009/04/06/queued-and-air-issues-part-ii/</link>
		<comments>http://www.sitepen.com/blog/2009/04/06/queued-and-air-issues-part-ii/#comments</comments>
		<pubDate>Mon, 06 Apr 2009 13:55:48 +0000</pubDate>
		<dc:creator>ttrenka</dc:creator>
		
		<category><![CDATA[Dojo]]></category>

		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[air]]></category>

		<category><![CDATA[api]]></category>

		<category><![CDATA[queued]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/2009/04/06/queued-and-air-issues-part-ii/</guid>
		<description><![CDATA[In Part I of Queued and AIR issues, I talked about some of the challenges we faced during the development of Queued, our AIR application that allows you to manage your Netflix queues.  In this post, I&#8217;ll discuss five other issues we ran across.
Dealing with the AIR Application Sandbox
One major issue we discovered, during [...]]]></description>
			<content:encoded><![CDATA[<p>In Part I of <a href="https://www.sitepen.com/blog/2009/04/01/queued-and-air-issues-part-i/">Queued and AIR issues</a>, I talked about some of the challenges we faced during the development of <a href="http://sitepen.com/labs/queued/">Queued</a>, our AIR application that allows you to manage your Netflix queues.  In this post, I&#8217;ll discuss five other issues we ran across.</p>
<h2>Dealing with the AIR Application Sandbox</h2>
<p>One major issue we discovered, during the development of the offline-to-online synchronization, was running head-first into the wall created by <a href="http://help.adobe.com/en_US/AIR/1.5/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7f05.html">the application sandbox</a>.  This sandbox is AIR&#8217;s mechanism for preventing any kind of scripting exploits within AIR applications, and it is very robust.  However, one of the major restrictions is the following:</p>
<blockquote><p>
For HTML content in the application security sandbox, there are limitations on using APIs that can dynamically transform strings into executable code after the code is loaded (after the onload event of the body element has been dispatched and the onload handler function has finished executing). This is to prevent the application from inadvertently injecting (and executing) code from non-application sources (such as potentially insecure network domains).<br />
&#8230;<br />
One restriction is in the use of the JavaScript eval() function. Once code in the application sandbox is loaded and after processing of the onload event handler, you can only use the eval() function in limited ways.
</p></blockquote>
<p>(For more information, you can <a href="http://help.adobe.com/en_US/AIR/1.5/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7f11.html#WS5b3ccc516d4fbf351e63e3d118676a3fc7-7fe7">check out the AIR documentation about security</a>.)</p>
<p>While we were aware of this restriction from previous work with AIR, this threw us for a curve when implementing the transaction queue.  The original design of the queue was to place the functions actually needed to accomplish a synchronization task within the database itself, so that when the user returned online, the database could simply be read and executed.  But without the ability to use <code>eval()</code> or the <code>new Function()</code> constructor, we could not use this approach.</p>
<p>Instead we created a function map:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #003366; font-weight: bold;">var</span> methods = <span style="color: #66cc66;">&#123;</span>
	rate: <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>args<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
		<span style="color: #000066; font-weight: bold;">return</span> qd.<span style="color: #006600;">service</span>.<span style="color: #006600;">titles</span>.<span style="color: #006600;">rate</span><span style="color: #66cc66;">&#40;</span>args<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>,
	add: <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>args<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
		<span style="color: #003366; font-weight: bold;">var</span> dfd = <span style="color: #003366; font-weight: bold;">new</span> dojo.<span style="color: #006600;">Deferred</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		qd.<span style="color: #006600;">app</span>.<span style="color: #006600;">queue</span>.<span style="color: #006600;">addMovieById</span><span style="color: #66cc66;">&#40;</span>args.<span style="color: #006600;">movieId</span>, <span style="color: #003366; font-weight: bold;">null</span>, args.<span style="color: #006600;">queue</span><span style="color: #66cc66;">&#41;</span>;
		setTimeout<span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
			dfd.<span style="color: #006600;">callback</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #66cc66;">&#125;</span>, <span style="color: #CC0000;">250</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000066; font-weight: bold;">return</span> dfd;
	<span style="color: #66cc66;">&#125;</span>,
	termAdd: <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>args<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
		<span style="color: #003366; font-weight: bold;">var</span> dfd = <span style="color: #003366; font-weight: bold;">new</span> dojo.<span style="color: #006600;">Deferred</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #003366; font-weight: bold;">var</span> queue = args.<span style="color: #006600;">queue</span>;
		args.<span style="color: #006600;">result</span> = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
			qd.<span style="color: #006600;">app</span>.<span style="color: #006600;">queue</span>.<span style="color: #006600;">addMovieById</span><span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span>.<span style="color: #006600;">guid</span>, <span style="color: #003366; font-weight: bold;">null</span>, queue<span style="color: #66cc66;">&#41;</span>;
			dfd.<span style="color: #006600;">callback</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #66cc66;">&#125;</span>;
		<span style="color: #000066; font-weight: bold;">delete</span> args.<span style="color: #006600;">queue</span>;
		qd.<span style="color: #006600;">service</span>.<span style="color: #006600;">titles</span>.<span style="color: #006600;">fetch</span><span style="color: #66cc66;">&#40;</span>args<span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000066; font-weight: bold;">return</span> dfd;
	<span style="color: #66cc66;">&#125;</span>,
	modify: <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>args<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
		<span style="color: #000066; font-weight: bold;">return</span> qd.<span style="color: #006600;">service</span>.<span style="color: #006600;">queues</span>.<span style="color: #006600;">modify</span><span style="color: #66cc66;">&#40;</span>args<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>,
	remove: <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>args<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
		<span style="color: #000066; font-weight: bold;">return</span> qd.<span style="color: #006600;">service</span>.<span style="color: #006600;">queues</span>.<span style="color: #006600;">remove</span><span style="color: #66cc66;">&#40;</span>args<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>,
	discs: <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
		<span style="color: #000066; font-weight: bold;">return</span> qd.<span style="color: #006600;">service</span>.<span style="color: #006600;">queues</span>.<span style="color: #006600;">discs</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span> max: <span style="color: #CC0000;">1</span> <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>,
	instant: <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
		<span style="color: #000066; font-weight: bold;">return</span> qd.<span style="color: #006600;">service</span>.<span style="color: #006600;">queues</span>.<span style="color: #006600;">instant</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span> max: <span style="color: #CC0000;">1</span> <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>;</pre></div></div>

<p>View the <a href="http://code.google.com/p/queued/source/browse/trunk/src/js/dev/qd/services/online.js">code that handles the offline sync</a>.</p>
<p>By writing out a function map in this matter, we could then store the <em>arguments</em> used with this map as JSON structures in the database (as well as the map key), and call it using JavaScript&#8217;s associative array syntax:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">dojo.<span style="color: #006600;">forEach</span><span style="color: #66cc66;">&#40;</span>data, <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> method = <span style="color: #000066; font-weight: bold;">item</span>.<span style="color: #006600;">method</span>;
    actions.<span style="color: #006600;">push</span><span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">if</span><span style="color: #66cc66;">&#40;</span>methods<span style="color: #66cc66;">&#91;</span>method<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
            <span style="color: #000066; font-weight: bold;">try</span> <span style="color: #66cc66;">&#123;</span>
                qd.<span style="color: #006600;">services</span>.<span style="color: #006600;">online</span>.<span style="color: #006600;">onSyncItemStart</span><span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span>.<span style="color: #000066;">prompt</span><span style="color: #66cc66;">&#41;</span>;
                methods<span style="color: #66cc66;">&#91;</span>method<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#40;</span>dojo.<span style="color: #006600;">fromJson</span><span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span>.<span style="color: #006600;">args</span>||<span style="color: #3366CC;">&quot;{}&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>
                    .<span style="color: #006600;">addCallback</span><span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
                        qd.<span style="color: #006600;">services</span>.<span style="color: #006600;">online</span>.<span style="color: #006600;">onSyncItemComplete</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
                    <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">addErrback</span><span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>err<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
                        console.<span style="color: #006600;">warn</span><span style="color: #66cc66;">&#40;</span>err<span style="color: #66cc66;">&#41;</span>;
                        qd.<span style="color: #006600;">services</span>.<span style="color: #006600;">online</span>.<span style="color: #006600;">onSyncItemComplete</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
                    <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
            <span style="color: #66cc66;">&#125;</span> <span style="color: #000066; font-weight: bold;">catch</span><span style="color: #66cc66;">&#40;</span>ex<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
                console.<span style="color: #006600;">warn</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;sync: &quot;</span>, ex<span style="color: #66cc66;">&#41;</span>;
            <span style="color: #66cc66;">&#125;</span>
        <span style="color: #66cc66;">&#125;</span>
    <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>By using the <a href="http://en.wikipedia.org/wiki/Associative_array">associative array</a> syntax, we were able to circumvent the sandbox restrictions put in place by AIR, and do the online sync in an easy-to-follow manner.  While this works fine for us, it is not an intuitive solution for most developers.</p>
<h2>Initial Window Placement</h2>
<p>One of the problems with the structure of an <a href="http://get.adobe.com/air">AIR</a> application is the way the manifest is used for compilation.  For those unfamiliar with AIR application development, a <a href="http://help.adobe.com/en_US/AIR/1.5/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7ecc.html">manifest</a> is the initial XML file AIR uses to compile an application into an executable format; it defines things like the version of the application, the publisher of an application, and other attributes AIR needs to make your HTML-based application into a usable application.  Among these attributes are the definitions of the initial window&mdash;both the size and the initial placement.</p>
<p>Most desktop applications are written using the following initialization routine:</p>
<ol>
<li>A splash screen is placed on the desktop</li>
<li>The application performs any initialization tasks it needs to&mdash;such as loading in parameters, defining/checking variables, and other things</li>
<li>When the initialization completes, the actual application interface is presented to the user.</li>
</ol>
<p>For a number of reasons, we decided to develop Queued without a splash screen.  We felt that we could complete all necessary initialization without seriously interfering with the user experience; splash screens have a tendency to delay user interaction to the point where it can be frustrating (as in, <em>It is my queue and I want to see it NOW</em>!), so our goal was to make it so you were connected to your information as absolutely fast as possible.</p>
<p>Unfortunately, one of the side effects of this approach is the inability to use basic features like the last x/y window coordinates of your previous usage of Queued.  Don&#8217;t get me wrong&mdash;we can capture that information and store it without any difficulty.  But usually that sort of thing is used during an initialization process, i.e. splash screen (from the user interface point-of-view), and because we decided not to use that approach, the main window for Queued will always appear in the same spot (with the same size) regardless of what you have done previously with the main window.</p>
<p>We felt (pretty strongly) that loading up the application as fast as possible was an acceptable trade-off to remembering the last settings of the window hosting the application.</p>
<h2>The ELS, performance, and serialization</h2>
<p>In Part I, I talked a bit about AIR&#8217;s <a href="http://help.adobe.com/en_US/AIR/1.5/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7e31.html">Encrypted Local Storage</a>, or ELS, and how we used it to set up an encrypted database without forcing user interaction.  This storage mechanism (similar to the Firefox browser storage or the proposed HTML5 feature) is essentially a cookie store that allows for larger data structures and limits; and it has been designed to make sure that the store is isolated by application and user (so 2 users on the same machine, using Queued, would each have their own ELS).  Thinking that using the ELS would be faster than using the encrypted database for certain things, we began using it not only to store the password of the database&mdash;but also for essential user information, such as your name, some of your preferences, and your queues.</p>
<p>We did not realize that this was A <em>Bad</em> Idea™.  On my own Netflix account, I have an average of 35 titles in my disc queue, and another 35 in my Instant queue.  All queue items in Queued are stored as a fairly complex JSON structure (see <a href="http://www.sitepen.com/blog/2009/03/26/queued-api-challenges/#more-667">this post</a> by my friend and colleague <a href="http://www.sitepen.com/blog/author/mwilcox">Mike Wilcox</a>) and because of this, a user&#8217;s queue information can get fairly large.  Adobe itself states (with regards to ELS size and performance):</p>
<blockquote><p>
The encrypted local store may perform more slowly if the stored data exceeds 10MB.
</p></blockquote>
<p>What we found was that it took a lot less data to make it perform slowly; saving my information (with my queues) was taking something on the order of 10 seconds to do for approximately 2.5MB of data, and was interrupting the user interface thread, providing an unacceptable user experience.</p>
<p>We solved this issue by pulling all of the user&#8217;s queue information and using the database instead to cache it.  Now we only use the ELS to store basic data&mdash;such as the user&#8217;s information, preferences and authorization info (soon we won&#8217;t be using the ELS at all but that is another story for another time).</p>
<h3>Serialization and the ELS</h3>
<p>Another issue with the ELS is the way objects are serialized and marshaled for it.  The ELS uses <a href="http://help.adobe.com/en_US/AIR/1.5/jslr/flash/utils/ByteArray.html">ByteArray</a>s for storage (presumably to facilitate the encryption process).  AIR&#8217;s ByteArray is pretty robust; it allows you to read and write all sorts of data types to the internal stream, taking care of the serialization process (i.e. converting a type into a concrete format) in a seamless manner.</p>
<p>Unfortunately, the serialization format AIR uses is the <a href="http://osflash.org/documentation/amf">ActionScript Message Format</a> (AMF).  For Flash, Flex and AIR apps written based on ActionScript objects, this is a great way of doing things.  But for native JavaScript objects, not so much&mdash;partially because AMF assumes existing class structures for marshaling (i.e. deserialization), and JavaScript object structures (such as the ones we use for defining things like titles and queue items) are essentially classless <a href="http://en.wikipedia.org/wiki/Mixin">mixins</a>.</p>
<p>In the end, we simply used Dojo&#8217;s <a href="http://docs.dojocampus.org/dojo/_base/json">JSON</a> handling facilities to both serialize and parse, and simply pushed things into the ELS as a string.</p>
<h2>Managing Queued&#8217;s Exit Events</h2>
<p>One of the coolest features of Queued is the Mini-Queue:</p>
<p><a href='http://www.sitepen.com/blog/wp-content/uploads/2009/03/miniqueue.png' title='Queued’s Mini-Queue window'><img src='http://www.sitepen.com/blog/wp-content/uploads/2009/03/miniqueue.png' alt='Queued’s Mini-Queue window' /></a></p>
<p>This is a chromeless window that shows you (at a glance) what you have at home, and can do other things (such as alerting you when Netflix receives or ships other titles).  It&#8217;s a neat piece of functionality that allows you to run Queued in the background without having to have the main window open all the time.</p>
<p>However, introducing a second window (particularly a chromeless one) into the application structure caused a number of management issues&mdash;in particular, dealing with the application&#8217;s <a href="http://help.adobe.com/en_US/AIR/1.5/jslr/flash/desktop/NativeApplication.html#event:exiting">exiting</a> event.  What we needed was a reliable way of controlling how Queued quit when showing the Mini-Queue but without showing the main application window, and we found that trying to use the <em>exiting</em> event seemed to be unreliable (certain operating system actions would cause the event not to fire, debugging it was a significant pain, and there were a number of other problems I won&#8217;t go into here).</p>
<p>In the end, we set up Queued so that if you have the Mini-Queue open, the only reliable way to exit the app was to use the Dock Icon/Taskbar tray to force the exit:</p>
<p><a href="http://www.sitepen.com/blog/wp-content/uploads/2009/03/ishot-5.jpg"><img src="http://www.sitepen.com/blog/wp-content/uploads/2009/03/ishot-5.jpg" border="0" /></a></p>
<p>We will probably revisit this in a future release of Queued.</p>
<h2>Tray/Dock Icon Loading and Menu Handling</h2>
<p>Speaking of the context menu attached to the tray or dock icon&#8230;we ran across an issue where the application icon that is supposed to appear in the tray of the Windows taskbar would not load correctly.  For loading the icons, we used <a href="http://code.google.com/p/dair/source/browse/trunk/js/dair/Icon.js">dAIR&#8217;s Icon</a> (from the <a href="http://code.google.com/p/dair">Dojo Extensions for Adobe AIR</a> library), which handles many of the basic AIR tasks in a convenient higher-level Dojo-esque manner.</p>
<p>For reasons still undetermined&mdash;though we&#8217;ve traced it to concurrent network activity&mdash;loading the icon images for the tray consistently failed when loading Queued.  Without being able to know when any kind of network activity is already in progress, the only solution we found was to retry the image load until successful (or until we reached a limit of retries).  This solution is less than ideal but It Works™.</p>
<h3>Tray menu handling</h3>
<p>Last but not least, one quirk of Adobe AIR is the separation between the <a href="http://help.adobe.com/en_US/AIR/1.5/jslr/flash/desktop/DockIcon.html">DockIcon</a> vs. the <a href="http://help.adobe.com/en_US/AIR/1.5/jslr/flash/desktop/SystemTrayIcon.html">SystemTrayIcon</a>.  Both classes are designed to support OS-based functionality; however, because of the nature of the DockIcon we ran into major issues when trying to determine if someone had opened the context menu attached to it.  </p>
<p>Simply put, the DockIcon does not support any kind of mouse click events, whereas the SystemTrayIcon does.</p>
<p>In the end, we simply wrote the system tray functionality to mimic the native behavior of the DockIcon.  We found this solution to be less than ideal, since what we <em>really</em> wanted was for the user to be able to close the main window of Queued, and have the icon/app indicator disappear from both the dock and the Windows taskbar (a la <a href="http://www.utorrent.com">uTorrent</a>).  Because of the behavior of the DockIcon, this was simply not possible to do under OS X.</p>
<p>A feature request improvement for Adobe AIR would be to implement an icon + menu that gets placed in the Menu Bar of OS X, and have that act the same way as the SystemTrayIcon class, something like this:</p>
<p><a href='http://www.sitepen.com/blog/wp-content/uploads/2009/03/menuicon.png' title='A menu bar menu example'><img src='http://www.sitepen.com/blog/wp-content/uploads/2009/03/menuicon.png' alt='A menu bar menu example' /></a></p>
<p>This would solve the aforementioned issue in a consistent manner.</p>
<h2>Conclusions</h2>
<p>Working with Adobe AIR was a bit of a treat, and we had a lot of fun creating Queued&mdash;but in many ways, we learned new lessons the hard way.  I hope talking about some of the issues we ran across during Queued&#8217;s development can help you when creating your own AIR-based applications!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2009/04/06/queued-and-air-issues-part-ii/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Queued: Theming</title>
		<link>http://www.sitepen.com/blog/2009/04/03/queued-theming/</link>
		<comments>http://www.sitepen.com/blog/2009/04/03/queued-theming/#comments</comments>
		<pubDate>Fri, 03 Apr 2009 07:01:15 +0000</pubDate>
		<dc:creator>canderson</dc:creator>
		
		<category><![CDATA[Dojo]]></category>

		<category><![CDATA[News]]></category>

		<category><![CDATA[UI Design]]></category>

		<category><![CDATA[air]]></category>

		<category><![CDATA[ajax]]></category>

		<category><![CDATA[queued]]></category>

		<category><![CDATA[CSS3]]></category>

		<category><![CDATA[webkit]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/2009/04/03/queued-theming/</guid>
		<description><![CDATA[As part of our series on how we built Queued, today we&#8217;re going to talk about theming the Queued application, and touch on a few examples of what made putting the skin on Queued so much fun.
The foundation for the beautiful theme for Queued was laid down by colleagues Damon Dimmick and Torrey Rice, and [...]]]></description>
			<content:encoded><![CDATA[<p>As part of our series on how we built Queued, today we&#8217;re going to talk about theming the Queued application, and touch on a few examples of what made putting the skin on Queued so much fun.</p>
<p>The foundation for the beautiful theme for Queued was laid down by colleagues Damon Dimmick and Torrey Rice, and their amazing wireframe and mockup work (respectively) provided the building blocks for laying down Queued&#8217;s skin. </p>
<h2>Powered by WebKit</h2>
<p>One of the advantages to building an Adobe AIR application that we can&#8217;t talk enough about is that you only have to develop for one layout engine.  Since Adobe uses WebKit to power the AIR runtime, we as developers get to take advantage of all of the mature, feature-rich goodness that comprises WebKit, including some of the things in the <a href="http://developer.apple.com/documentation/AppleApplications/Reference/SafariCSSRef/Articles/StandardCSSProperties.html#//apple_ref/doc/uid/TP30001266-SW1">WebKit Supported CSS Properties</a>.  Additionally, Adobe has a <a href="http://help.adobe.com/en_US/AIR/1.5/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7eb0.html">document</a> that describes the extensions to CSS that AIR uses, which my colleague Sam Foster will talk about in greater detail in an upcoming article.  In our development process, we found that AIR&mdash;while not being able to take advantage of all of the <a href="http://developer.apple.com/documentation/AppleApplications/Reference/SafariCSSRef/Articles/StandardCSSProperties.html#//apple_ref/doc/uid/TP30001266-SW1">WebKit supported CSS properties</a>&mdash;still provided us a good chunk of styling advantages that we were able to implement to make the theming job quicker and easier.</p>
<h2>Keeping it Local</h2>
<p>One of the things we were able to do with Queued is to take away some of the application&#8217;s workload in regards to box art image files.  Rather than saturate the wire with this data, we use a local store to house your box art images (along with other data such as preferences, etc.) to help keep Queued&#8217;s online presence nimble.</p>
<p><img src='http://www.sitepen.com/blog/wp-content/uploads/2009/03/localstore.png' alt='localstore.png' /></p>
<h2>PNG Transparency</h2>
<p>Building applications for use with Adobe AIR&#8217;s WebKit engine also means that we don&#8217;t have to worry about IE 6&#8217;s PNG alpha transparency issues.  Not having to deal with this thorn in the side allowed us to use drop shadows to our heart&#8217;s content, and allowed the movie information pop-up to easily achieve the look we were after in our mockups.</p>
<p><img src='http://www.sitepen.com/blog/wp-content/uploads/2009/03/movieinfo.png' alt='movieinfo.png' /></p>
<h2>CSS 3, How We Love Thee</h2>
<p>Every developer on the Queued project remarked how nice it was to have to support only one layout engine; theming Queued has certainly left us spoiled in this regard.  When styling Queued, we were also able to take advantage of some of the CSS 3 selectors and properties that are supported by WebKit.  One of the things we wanted to do was prevent the user from being able to highlight areas of the application that they really didn&#8217;t need to.  By using -webkit-user-select, we were able to tailor the user-selectable content to our needs.</p>
<p><img src='http://www.sitepen.com/blog/wp-content/uploads/2009/03/textselect.png' alt='textselect.png' /></p>

<div class="wp_syntax"><div class="code"><pre class="css">html, body, <span style="color: #cc00cc;">#layoutNode</span> <span style="color: #66cc66;">&#123;</span>
	width<span style="color: #3333ff;">:<span style="color: #933;">100</span></span>%;
	height<span style="color: #3333ff;">:<span style="color: #933;">100</span></span>%;
	overflow<span style="color: #3333ff;">:hidden</span>;
	-webkit-user-select<span style="color: #3333ff;">:none</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #cc00cc;">#movieInfoDialogNode</span> <span style="color: #6666ff;">.info</span> <span style="color: #66cc66;">&#123;</span>
	position<span style="color: #3333ff;">:absolute</span>;
	top<span style="color: #3333ff;">:<span style="color: #933;">46px</span></span>;
	right<span style="color: #3333ff;">:<span style="color: #933;">8px</span></span>;
	width<span style="color: #3333ff;">:<span style="color: #933;">560px</span></span>;
	height<span style="color: #3333ff;">:<span style="color: #933;">412px</span></span>;
	padding-right<span style="color: #3333ff;">:<span style="color: #933;">40px</span></span>;
	overflow-y<span style="color: #3333ff;">:auto</span>;
	-webkit-user-select<span style="color: #3333ff;">:text</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #cc00cc;">#searchResultsList</span> <span style="color: #6666ff;">.movie</span> <span style="color: #6666ff;">.info</span> <span style="color: #66cc66;">&#123;</span>
	display<span style="color: #3333ff;">:block</span>;
	position<span style="color: #3333ff;">:absolute</span>;
	left<span style="color: #3333ff;">:<span style="color: #933;">150px</span></span>;
	right<span style="color: #3333ff;">:<span style="color: #933;">8px</span></span>;
	padding-top<span style="color: #3333ff;">:<span style="color: #933;">7px</span></span>;
	-webkit-user-select<span style="color: #3333ff;">:text</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>We also took advantage of WebKit&#8217;s border-radius support, using it in areas like the search input background.</p>
<p><img src='http://www.sitepen.com/blog/wp-content/uploads/2009/03/searchbar.png' alt='searchbar.png' /></p>

<div class="wp_syntax"><div class="code"><pre class="css"><span style="color: #cc00cc;">#searchBar</span> input <span style="color: #66cc66;">&#123;</span>
	width<span style="color: #3333ff;">:<span style="color: #933;">238px</span></span>;
	padding<span style="color: #3333ff;">:<span style="color: #933;">5px</span></span> <span style="color: #933;">8px</span>;
	outline<span style="color: #3333ff;">:none</span>;
	-webkit-border-radius<span style="color: #3333ff;">:<span style="color: #933;">12px</span></span>;
	border<span style="color: #3333ff;">:<span style="color: #933;">1px</span></span> <span style="color: #993333;">solid</span> <span style="color: #cc00cc;">#C60000</span>;
	<span style="color: #000000; font-weight: bold;">color</span>: <span style="color: #cc00cc;">#AFAFAF</span>;
	background<span style="color: #3333ff;">:url</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;../img/searchBg.png&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333;">repeat-x</span> <span style="color: #000000; font-weight: bold;">left</span> <span style="color: #000000; font-weight: bold;">top</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>To prevent movie titles with really long names from breaking our layout, we used text-overflow.  We also used text-overflow in other areas of the application, such as login input.</p>
<p><img src='http://www.sitepen.com/blog/wp-content/uploads/2009/03/searchtruncate.png' alt='searchtruncate.png' /></p>

<div class="wp_syntax"><div class="code"><pre class="css"><span style="color: #cc00cc;">#searchAutoSuggestList</span> li <span style="color: #66cc66;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">color</span>:<span style="color: #cc00cc;">#bf0000</span>;
	margin<span style="color: #3333ff;">:<span style="color: #933;">0</span></span> <span style="color: #933;">6px</span>;
	padding<span style="color: #3333ff;">:<span style="color: #933;">0</span></span> <span style="color: #933;">3px</span>;
	width<span style="color: #3333ff;">:<span style="color: #933;">196px</span></span>;
	<span style="color: #000000; font-weight: bold;">white-space</span>: <span style="color: #993333;">nowrap</span>;
	overflow<span style="color: #3333ff;">:hidden</span>;
	text-overflow<span style="color: #3333ff;">:ellipsis</span>;
	-webkit-text-overflow<span style="color: #3333ff;">:ellipsis</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Another great example of a CSS 3 property that we were able to use is support for multiple backgrounds.  We wanted to style the selected nav element of the application with a &#8220;glowing&#8221; type of effect coming out from the left and right sides of the element.  Rather than having to use multiple divs to get this done, we were able to use multiple backgrounds to produce the effect.  The following three images show the selected element with no background image, one background image (positioned top right), and two background images (one positioned top right, the other top left), ultimately providing the glowing effect we had on our mockups.</p>
<p><img src='http://www.sitepen.com/blog/wp-content/uploads/2009/03/multiplebg.png' alt='multiplebg.png' /></p>

<div class="wp_syntax"><div class="code"><pre class="css"><span style="color: #cc00cc;">#topMoviesSubNav</span> ul li<span style="color: #6666ff;">.selected</span>,
<span style="color: #cc00cc;">#queSubNav</span> ul li<span style="color: #6666ff;">.selected</span>,
<span style="color: #cc00cc;">#authSubNav</span> ul li<span style="color: #6666ff;">.selected</span>,
<span style="color: #cc00cc;">#prefsSubNav</span> ul li<span style="color: #6666ff;">.selected</span> <span style="color: #66cc66;">&#123;</span>
	background<span style="color: #3333ff;">:url</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;../img/subMenuActiveBorder.png&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333;">repeat-y</span> <span style="color: #000000; font-weight: bold;">top</span> <span style="color: #000000; font-weight: bold;">right</span>, 
        <span style="color: #993333;">url</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;../img/subMenuActiveBorder.png&quot;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333;">repeat-y</span> <span style="color: #000000; font-weight: bold;">top</span> <span style="color: #000000; font-weight: bold;">left</span>;
	position<span style="color: #3333ff;">:relative</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<h2>Conclusion</h2>
<p>Theming Queued was a tremendous amount of work, but by taking advantage of local storage, having only one layout engine to work with, and harnessing some of the CSS 3 goodies supported by AIR&#8217;s version of WebKit, that workload was decreased.  This allowed us to get the job done quicker, and we had a lot of fun along the way.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2009/04/03/queued-theming/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Stocker: Advanced Dojo Made Easy</title>
		<link>http://www.sitepen.com/blog/2009/04/01/stocker-advanced-dojo-made-easy/</link>
		<comments>http://www.sitepen.com/blog/2009/04/01/stocker-advanced-dojo-made-easy/#comments</comments>
		<pubDate>Wed, 01 Apr 2009 23:41:02 +0000</pubDate>
		<dc:creator>mwilcox</dc:creator>
		
		<category><![CDATA[Cometd]]></category>

		<category><![CDATA[Dojo]]></category>

		<category><![CDATA[Dojo Grid]]></category>

		<category><![CDATA[News]]></category>

		<category><![CDATA[Persevere]]></category>

		<category><![CDATA[Training]]></category>

		<category><![CDATA[Vector Graphics]]></category>

		<category><![CDATA[ajax]]></category>

		<category><![CDATA[api]]></category>

		<category><![CDATA[BorderContainer]]></category>

		<category><![CDATA[DataChart]]></category>

		<category><![CDATA[Stocker]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/2009/04/01/stocker-advanced-dojo-made-easy/</guid>
		<description><![CDATA[SitePen is excited to announce Stocker, which demonstrates some of the more advanced capabilities of Dojo, including the newly released DataChart, the DataGrid, Data Store, Comet, Persevere, and BorderContainer. SitePen is also offering a one-day workshop where you will learn how to create Stocker yourself, but I&#8217;m here to give you a sneak peak of [...]]]></description>
			<content:encoded><![CDATA[<p>SitePen is excited to announce <a href="http://persevere.sitepen.com/stocker.html">Stocker</a>, which demonstrates some of the more advanced capabilities of Dojo, including the newly released DataChart, the DataGrid, Data Store, Comet, Persevere, and BorderContainer. SitePen is also offering a one-day workshop where you will learn how to create Stocker yourself, but I&#8217;m here to give you a sneak peak of what Stocker is and how it works.</p>
<p>Stocker uses these technologies to emulate a stock monitoring application. We&#8217;re using made up data, but that&#8217;s actually more interesting. The Persevere server generates new stock items at certain intervals, and then pushes them to the browser with Comet. Then the Data Store updates its items and triggers an <code>onSet</code> notification. The DataGrid and DataChart are both connected to the same store, and are listening to that event. They then update their displays and show the stock items and their latest data.</p>
<p><img src='http://www.sitepen.com/blog/wp-content/uploads/2009/03/stocker.jpg' alt='Stocker' /></p>
<h2>Persevere</h2>
<p><a href="http://www.sitepen.com/labs/persevere.php/">Persevere</a>, which we chose to use inside the robust Jetty web server, allows us to quickly develop a data-driven web application that can directly interface with Dojo, without having to setup a relational database and create Ajax request handlers. It&#8217;s similar to Jaxer, in that it is a rich interactive server-side JavaScript environment (though Persevere uses Rhino), and is accessible via JSON-RPC, meaning Persevere is great for pure Ajax front-ends. SitePen&#8217;s Kris Zyp has a <a href="http://www.sitepen.com/blog/category/persevere/">large number of articles explaining how Persevere works</a>. </p>
<p>Persevere uses JSON Schema for defining the structure of class instances. Stocker uses one class schema definition that looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #3366CC;">&quot;name&quot;</span>:<span style="color: #3366CC;">&quot;Stock&quot;</span>,
<span style="color: #3366CC;">&quot;extends&quot;</span>:<span style="color: #3366CC;">&quot;Object&quot;</span>,
<span style="color: #3366CC;">&quot;schema&quot;</span>:<span style="color: #66cc66;">&#123;</span>
	<span style="color: #3366CC;">&quot;prototype&quot;</span>:<span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span>,
	<span style="color: #3366CC;">&quot;instances&quot;</span>:<span style="color: #66cc66;">&#123;</span><span style="color: #3366CC;">&quot;$ref&quot;</span>:<span style="color: #3366CC;">&quot;../Stock/&quot;</span><span style="color: #66cc66;">&#125;</span>,
	<span style="color: #3366CC;">&quot;extends&quot;</span>:<span style="color: #66cc66;">&#123;</span><span style="color: #3366CC;">&quot;$ref&quot;</span>:<span style="color: #3366CC;">&quot;../Class/Object&quot;</span><span style="color: #66cc66;">&#125;</span>,
	<span style="color: #3366CC;">&quot;go&quot;</span>:<span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>amount<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
		startUpdateStock<span style="color: #66cc66;">&#40;</span>amount<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>As you can see, you can even include methods in the schema, which can be used for a variety of things. The method <code>go()</code> shown here calls the server-side method <code>startUpdateStock()</code>. You can access this method from the command-line through this static class:</p>

<div class="wp_syntax"><div class="code"><pre class="bash">JS&gt; Stock.go<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>;</pre></div></div>

<p>In the server-side code, we start with a set of simple objects on which we base the Stock data. An example of one such object looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #66cc66;">&#123;</span> symbol:<span style="color: #3366CC;">&quot;ANDT&quot;</span>, <span style="color: #000066;">name</span>:<span style="color: #3366CC;">&quot;Anduct&quot;</span>, price:<span style="color: #CC0000;">3.13</span> <span style="color: #66cc66;">&#125;</span></pre></div></div>

<p><em>Note: Stocker uses more properties than this, but it is edited for clarity.</em></p>
<p>When <code>startUpdateStock()</code> is fired the first time, these objects are read in, randomized, and then saved as a Stock instance. When saved, the instance is written to a table and persisted. Basically it works like this: think of <em>Stock</em> as your SQL table, and each <em>instance</em> as a row of data. The columns in the table are represented by the <em>properties</em> that you see in the object above, such as symbol or price. And all you have to do to write to this table is:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #003366; font-weight: bold;">new</span> Stock<span style="color: #66cc66;">&#40;</span> <span style="color: #66cc66;">&#123;</span> symbol:<span style="color: #3366CC;">&quot;ANDT&quot;</span>, <span style="color: #000066;">name</span>:<span style="color: #3366CC;">&quot;Anduct&quot;</span>, price:<span style="color: #CC0000;">3.13</span> <span style="color: #66cc66;">&#125;</span> <span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>And modifying the data is just as easy. We loop through all of the instances in the Stock class (or table) and change the properties of the object. Persevere even automatically commits the changes for you, so this is all you need to do:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">Stock.<span style="color: #006600;">instances</span>.<span style="color: #006600;">forEach</span><span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>instance<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
	<span style="color: #003366; font-weight: bold;">var</span> m = randomizeStockData<span style="color: #66cc66;">&#40;</span>instance<span style="color: #66cc66;">&#41;</span>;
	<span style="color: #000066; font-weight: bold;">for</span><span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> nm <span style="color: #000066; font-weight: bold;">in</span> m<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
		instance<span style="color: #66cc66;">&#91;</span>nm<span style="color: #66cc66;">&#93;</span> = m<span style="color: #66cc66;">&#91;</span>nm<span style="color: #66cc66;">&#93;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>Notice we were able to use <code>forEach</code> on the instance array. We&#8217;re able to use all the functionality of <a href="https://developer.mozilla.org/en/New_in_JavaScript_1.7">Mozilla JavaScript 1.7</a>, like array functions or getters and setters, and don&#8217;t have to worry about cross-browser issues when writing server-side JavaScript in Persevere.</p>
<h2>Comet</h2>
<p>In Stocker, we created an arbitrary amount of six Stock instances. Once they are created, the client-side can now fetch them and access their properties using the <code>dojox.data.PersevereStore</code>. Of all the data stores available in Dojo, the PersevereStore is my favorite. You pretty much declare your store with a pointer to your class, do your fetch, and you&#8217;re done:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #003366; font-weight: bold;">var</span> store = <span style="color: #003366; font-weight: bold;">new</span> dojox.<span style="color: #006600;">data</span>.<span style="color: #006600;">PersevereStore</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span>target:<span style="color: #3366CC;">&quot;/Stock/&quot;</span><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
store.<span style="color: #006600;">fetch</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span>query:<span style="color: #3366CC;">&quot;[?symbol='*']&quot;</span>, onComplete: <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>_items<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
	console.<span style="color: #006600;">log</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;fetched:&quot;</span>, items<span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>PersevereStore provides you with a connection to the server via <a href="http://www.sitepen.com/technology/">Comet</a>. When we randomized our stock data on the Persevere server, this committed the change to the database. These changes are then pushed to the browser. You can listen for these changes in the <code>onSet</code> event of the PersevereStore:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">dojo.<span style="color: #006600;">connect</span><span style="color: #66cc66;">&#40;</span>store, <span style="color: #3366CC;">&quot;onSet&quot;</span>, <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>data<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
	console.<span style="color: #006600;">log</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;onSet:&quot;</span>, data<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<h2>DataGrid</h2>
<p>Now it&#8217;s time to start wiring up the user interface, and believe it or not, things get easier here. The <a href="http://www.sitepen.com/blog/category/dojo-grid/">DataGrid</a> is largely the work of <a href="http://www.sitepen.com/blog/author/bforbes/">Bryan Forbes</a> and Nathan Toone, and is a first class user interface component. We started with the HTML structure that matched the properties we wanted to display from our Stock instances:</p>

<div class="wp_syntax"><div class="code"><pre class="html4strict"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;table</span> dojoType=<span style="color: #ff0000;">&quot;dojox.grid.DataGrid&quot;</span> <span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;thead&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tr&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;th</span> field=<span style="color: #ff0000;">&quot;name&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Stock Name<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/th&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;th</span> field=<span style="color: #ff0000;">&quot;symbol&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Symbol<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/th&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;th</span> field=<span style="color: #ff0000;">&quot;price&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>Price<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/th&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tr&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;</span>/thead&gt;</span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/table&gt;</span></span></pre></div></div>

<p>You could also add a store and fetch attribute, but we opted to hook this up within the code:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">dojo.<span style="color: #006600;">addOnLoad</span><span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
	grid.<span style="color: #006600;">setStore</span><span style="color: #66cc66;">&#40;</span>store, <span style="color: #3366CC;">&quot;[?symbol='*']&quot;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>The DataGrid has a built in fetch which grabs the current stock instances from Persevere, and then updates the items when the store&#8217;s onSet event is fired.</p>
<p>We did some CSS styling so the Grid would match our Stocker theme, and we were done with the Grid!</p>
<h2>DataChart</h2>
<p>The DataChart is brand new for Dojo 1.3, was created by yours truly, and was built specifically for Stocker, as it was obvious that charting was missing the ease of implementation that DataGrid provides. DojoX has an amazing vector graphics charting system written mainly by <a href="http://www.sitepen.com/blog/author/elazutkin/">Eugene Lazutkin</a>. It has a rich API that allows for maximum customization. However, DojoX charts didn&#8217;t support data stores, and while heavy customization is good in some cases, it can also create a barrier of entry for new developers. DataChart provides that interface between the two, all while supporting Dojo Data. I did a <a href="http://www.sitepen.com/blog/2009/03/30/introducing-dojox-datachart/">full write-up of DataChart</a> in a previous post. The intent was to make DataChart as easy to setup as the DataGrid:</p>

<div class="wp_syntax"><div class="code"><pre class="html4strict"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;div</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;chartNode&quot;</span> <span style="color: #000066;">style</span>=<span style="color: #ff0000;">&quot;width: 600px; height: 400px;&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/div&gt;</span></span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="javascript">chart = <span style="color: #003366; font-weight: bold;">new</span> dojox.<span style="color: #006600;">charting</span>.<span style="color: #006600;">DataChart</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;lines&quot;</span>, chartDefault.<span style="color: #006600;">chart</span><span style="color: #66cc66;">&#41;</span>;
chart.<span style="color: #006600;">setStore</span><span style="color: #66cc66;">&#40;</span>store, <span style="color: #3366CC;">&quot;[?symbol='*']&quot;</span>, <span style="color: #3366CC;">&quot;price&quot;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>There is also some custom code that places chart legends inline with their respective items in the Grid. There&#8217;s also some code that handles switching between some of the chart types (just to be fancy). But other than that, we were done with charts!</p>
<h2>BorderContainer</h2>
<p>To get the BorderContainer to work for you, you have to understand that it supports subsets of two different designs, <em>headline</em> or <em>sidebar</em>. If you want the sidebar pane to extend from the top of the layout to the bottom, you&#8217;d naturally use <em>sidebar</em>. If you want the header and footer to extend the entire width, you use <em>headline</em>. Within either layout you have five regions: <em>top, bottom, left, right, and center</em>. The center pane stretches to fit, so you set the widths or heights of all panes but that one. Each region can either be a ContentPane or another BorderContainer. Stocker is slightly more complicated than standard layouts allow, so we use a nested BorderContainer.</p>
<p>What follows is the structure of the Stocker layout. For readability, dojoType is type, BorderContainer is BC and ContentPane is CP.  Stocker uses the <em>headline</em> design which is the default, so it need not be not set. Its center pane is another BorderContainer with a <em>top</em> and <em>center</em>.</p>

<div class="wp_syntax"><div class="code"><pre class="html4strict"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;div</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;BC&quot;</span> gutters=<span style="color: #ff0000;">&quot;false&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>                                     
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;div</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;CP&quot;</span> region=<span style="color: #ff0000;">&quot;top&quot;</span> splitter=<span style="color: #ff0000;">&quot;false&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        Header
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/div&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;div</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;CP&quot;</span> gutters=<span style="color: #ff0000;">&quot;true&quot;</span> region=<span style="color: #ff0000;">&quot;left&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        Sidebar
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/div&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;div</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;BC&quot;</span>  gutters=<span style="color: #ff0000;">&quot;false&quot;</span> region=<span style="color: #ff0000;">&quot;center&quot;</span> liveSplitters=<span style="color: #ff0000;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;div</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;gridPane&quot;</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;CP&quot;</span> region=<span style="color: #ff0000;">&quot;top&quot;</span> splitter=<span style="color: #ff0000;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            Grid
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/div&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;div</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;CP&quot;</span> region=<span style="color: #ff0000;">&quot;center&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            Chart
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/div&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/div&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;div</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;CP&quot;</span> region=<span style="color: #ff0000;">&quot;bottom&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        Footer
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/div&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/div&gt;</span></span></pre></div></div>

<p>All children of a BorderContainer have an attribute region, which is the location in the design. BorderContainer&#8217;s have two other attributes: <code>liveSplitters</code> and <code>gutters</code>. Setting <code>gutters</code> to true puts a margin around it. The Stocker margins are handled in the CSS so these are set to false. The param <code>liveSplitters</code> indicates that one or more of the children will be resizable. A resizable pane acts much like the framesets of yesteryear, that had dividers between them that you could grab and drag to resize the frames.</p>
<p>Therefore, child panes can have the attribute <code>splitter=true</code>, which allows the user to resize it. It&#8217;s not obvious which child panes should get this attribute, since the splitter is shared amongst two panes. The trick to knowing is that the center pane, since it&#8217;s always stretchy, never gets this attribute&mdash;it is always applied to the pane that shares the splitter with it. </p>
<p>The DataGrid and DataChart were inserted in their proper ContentPane containers, the buttons for chart switching were placed in the sidebar, and the header and footer content was implemented. We launched the Persevere server, opened Stocker in our browser and watched the updates!</p>
<h2>Conclusion</h2>
<p><a href="http://persevere.sitepen.com/stocker.html">Stocker</a> was created to show the power of Dojo and some of it&#8217;s more advanced components, and how easily they can be implemented in your site or web application.  We&#8217;ll also be talking about Stocker and Dojo in a number of <a href="/events/">upcoming conference talks</a> this year.  If you&#8217;re interested in learning more about Stocker and how to put it together, <a href="/contact/">drop us a line</a>!</p>
<p>SitePen has workshops planned in various locations around world, and we&#8217;d love it if you could join us.  You&#8217;ll learn everything you need to build Stocker and more at the following one-day Intro to Dojo, Charts, Grids, and Comet workshops:</p>
<ul>
<li><a href="http://dojosydneyworkshop.eventbrite.com/">Sydney, Australia, April 23, 2009</a></li>
<li><a href="http://skillsmatter.com/event/ajax-ria/progressive-web-tutorials">London, England, May 13, 2009</a></li>
<li>Stockholm, Sweden, May 26, 2009</a></li>
<li>Milan, Italy, June 8, 2009</li>
<li>Paris, France, June 10, 2009</li>
</ul>
<p>Or, join us for a special <a href="http://www.sitepen.com/blog/2009/03/20/munich-dojo-workshop/">two-day Dojo Workshop in Munich, Germany, May 7-8, 2009</a> with the uxebu team.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2009/04/01/stocker-advanced-dojo-made-easy/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Queued and AIR Issues, Part I</title>
		<link>http://www.sitepen.com/blog/2009/04/01/queued-and-air-issues-part-i/</link>
		<comments>http://www.sitepen.com/blog/2009/04/01/queued-and-air-issues-part-i/#comments</comments>
		<pubDate>Wed, 01 Apr 2009 07:04:43 +0000</pubDate>
		<dc:creator>ttrenka</dc:creator>
		
		<category><![CDATA[Dojo]]></category>

		<category><![CDATA[air]]></category>

		<category><![CDATA[api]]></category>

		<category><![CDATA[queued]]></category>

		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/2009/04/01/queued-and-air-issues-part-i/</guid>
		<description><![CDATA[During the course of developing Queued, we ran across a number of challenges developing with AIR that we needed to solve.  Some were very difficult to get around, while others were the result of our team needing to think outside the web-based paradigm.  In this post, I&#8217;ll talk about four issues we ran [...]]]></description>
			<content:encoded><![CDATA[<p>During the course of developing <a href="http://sitepen.com/labs/queued">Queued</a>, we ran across a number of challenges developing with <a href="http://get.adobe.com/air">AIR</a> that we needed to solve.  Some were very difficult to get around, while others were the result of our team needing to think outside the web-based paradigm.  In this post, I&#8217;ll talk about four issues we ran across that ended up shaping part of the <a href="http://code.google.com/p/queued">Queued codebase</a>.</p>
<h2>Cross-Window Communication: the OAuth Handshake</h2>
<p>One of the most challenging issues we needed to solve was how to do the <a href="http://developer.netflix.com/docs/Security#0_18325">OAuth handshake with Netflix</a>.  As a quick review, the handshake is a process in which the user is directed to a web page on the application&#8217;s server&mdash;where they can enter their authentication information and receive a token in response:</p>
<p><a href='http://www.sitepen.com/blog/wp-content/uploads/2009/03/handshake.jpg' title='Queued’s OAuth handshake'><img src='http://www.sitepen.com/blog/wp-content/uploads/2009/03/handshake.jpg' alt='Queued’s OAuth handshake' /></a></p>
<h3>The Problem</h3>
<p>Adobe has done a great job in melding the web development paradigm with the desktop application paradigm; among the things that they&#8217;ve done is to apply some of the same sandbox security principles to any window created that applies to most browsers.  Unfortunately for us, part of this sandbox applies to any window that loads an HTML page that does not originate from the same domain&mdash;which meant that when we load the authorization page from Netflix&#8217;s servers, <em>we no longer had any kind of script or event access to that window</em>.  This includes access to things like the <em>window.onload</em> event&#8230;which meant that we had no real way of knowing what happens within the window.</p>
<p>Unfortunately, the OAuth handshake is designed such that the user is normally redirected to a web page on the originating server, with a parameter passed to it that the originating server then uses to redirect the user back with an access token.</p>
<h3>The Solution</h3>
<p>What we discovered was that we had access to the created window&#8217;s <code>window.location</code> property and the <em>onClose</em> event of the window object we used, so in the end my friend and colleague <a href="http://www.sitepen.com/blog/author/mwilcox/">Mike Wilcox</a> simply polled the open window for a change in URL.  Here&#8217;s the code in question (abbreviated):</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #003366; font-weight: bold;">var</span> seenOnce = <span style="color: #003366; font-weight: bold;">false</span>;
<span style="color: #003366; font-weight: bold;">var</span> v = setInterval<span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
	<span style="color: #003366; font-weight: bold;">var</span> wurl = win1._window.<span style="color: #006600;">location</span>;
	<span style="color: #000066; font-weight: bold;">if</span><span style="color: #66cc66;">&#40;</span>wurl != url<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
		<span style="color: #000066; font-weight: bold;">if</span><span style="color: #66cc66;">&#40;</span>!seenOnce &amp;&amp; wurl==<span style="color: #3366CC;">&quot;https://api-user.netflix.com/oauth/login&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
			seenOnce = <span style="color: #003366; font-weight: bold;">true</span>;
			<span style="color: #000066; font-weight: bold;">return</span>;
		<span style="color: #66cc66;">&#125;</span> 
		<span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span><span style="color: #66cc66;">&#40;</span>wurl==<span style="color: #3366CC;">&quot;http://www.netflix.com/TermsOfUse&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
			<span style="color: #000066; font-weight: bold;">return</span>;
		<span style="color: #66cc66;">&#125;</span>
		<span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span><span style="color: #66cc66;">&#40;</span>wurl.<span style="color: #006600;">indexOf</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;Failed&quot;</span><span style="color: #66cc66;">&#41;</span>&gt;<span style="color: #CC0000;">0</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
			<span style="color: #000066; font-weight: bold;">return</span>;
		<span style="color: #66cc66;">&#125;</span>
		clearInterval<span style="color: #66cc66;">&#40;</span>v<span style="color: #66cc66;">&#41;</span>;
		v = <span style="color: #003366; font-weight: bold;">null</span>;
		win1.<span style="color: #000066;">close</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>, <span style="color: #CC0000;">1000</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #003366; font-weight: bold;">var</span> c2 = dojo.<span style="color: #006600;">connect</span><span style="color: #66cc66;">&#40;</span>win1, <span style="color: #3366CC;">&quot;onClose&quot;</span>, <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
	<span style="color: #000066; font-weight: bold;">if</span><span style="color: #66cc66;">&#40;</span>v<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
		dfd.<span style="color: #006600;">errback</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;user&quot;</span><span style="color: #66cc66;">&#41;</span>;
		clearInterval<span style="color: #66cc66;">&#40;</span>v<span style="color: #66cc66;">&#41;</span>;
		dojo.<span style="color: #006600;">disconnect</span><span style="color: #66cc66;">&#40;</span>c2<span style="color: #66cc66;">&#41;</span>;
		<span style="color: #000066; font-weight: bold;">return</span>;
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #009900; font-style: italic;">//	we're good to go, so go get the access token</span>
	dojo.<span style="color: #006600;">xhrGet</span><span style="color: #66cc66;">&#40;</span>dojox.<span style="color: #006600;">io</span>.<span style="color: #006600;">OAuth</span>.<span style="color: #006600;">sign</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;GET&quot;</span>, <span style="color: #66cc66;">&#123;</span>
		url: <span style="color: #3366CC;">&quot;http://api.netflix.com/oauth/access_token&quot;</span>,
		handleAs: <span style="color: #3366CC;">&quot;text&quot;</span>,
		error: <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>err, ioArgs<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
			dfd.<span style="color: #006600;">errback</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;auth&quot;</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #66cc66;">&#125;</span>,
		load: <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>response, ioArgs<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
			<span style="color: #003366; font-weight: bold;">var</span> a = response.<span style="color: #006600;">split</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;&amp;&quot;</span><span style="color: #66cc66;">&#41;</span>, o = <span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span>;
			dojo.<span style="color: #006600;">forEach</span><span style="color: #66cc66;">&#40;</span>a, <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
				<span style="color: #003366; font-weight: bold;">var</span> p = <span style="color: #000066; font-weight: bold;">item</span>.<span style="color: #006600;">split</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;=&quot;</span><span style="color: #66cc66;">&#41;</span>;
				o<span style="color: #66cc66;">&#91;</span>p<span style="color: #66cc66;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#93;</span> = unescape<span style="color: #66cc66;">&#40;</span>p<span style="color: #66cc66;">&#91;</span><span style="color: #CC0000;">1</span><span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span>;
			<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
			qd.<span style="color: #006600;">app</span>.<span style="color: #006600;">authorize</span><span style="color: #66cc66;">&#40;</span>o.<span style="color: #006600;">oauth_token</span>,
				 o.<span style="color: #006600;">oauth_token_secret</span>, o.<span style="color: #006600;">user_id</span><span style="color: #66cc66;">&#41;</span>;
			dfd.<span style="color: #006600;">callback</span><span style="color: #66cc66;">&#40;</span>o.<span style="color: #006600;">user_id</span><span style="color: #66cc66;">&#41;</span>;
		<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>, token<span style="color: #66cc66;">&#41;</span>, <span style="color: #003366; font-weight: bold;">false</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>What the above code does is poll for a change in the URL of the opened window, and acts upon that change. If the boolean <em>seenOnce</em> ends up as true, we know that the user has authorized Queued for access to their Netflix information, and can finalize the OAuth handshake by getting the actual access token using <code>dojo.xhrGet</code> and <code>dojox.io.OAuth</code>.</p>
<h2>dojo.connect vs. AIR&#8217;s EventListener</h2>
<p>Another problem we ran across was the fact that all of the AIR objects made available to you during development were essentially incompatible with Dojo&#8217;s signals and slots workhorse, <a href="http://docs.dojocampus.org/dojo/connect">dojo.connect</a>.  For those who don&#8217;t know Dojo all that well, <code>dojo.connect</code> is an ingenious way of attaching functions to other functions.  It does this by swapping out the original function with another one, that will execute a queue of <em>connected</em> functions that have been applied by <code>connect</code>.</p>
<h3>The Problem</h3>
<p>The issue here is that dojo.connect assumes that the object being connected to is a JavaScript Function object; however, methods on AIR objects <em>are not true JavaScript Function objects at all</em>.  This basically means that the following code example will not compile with AIR:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">dojo.<span style="color: #006600;">connect</span><span style="color: #66cc66;">&#40;</span>air.<span style="color: #006600;">NativeApplication</span>.<span style="color: #006600;">nativeApplication</span>, air.<span style="color: #006600;">Event</span>.<span style="color: #006600;">USER_IDLE</span>, 
	<span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>evt<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
		doSomething<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>Coming from a pure Ajax development environment, this can throw anyone for a curve.</p>
<h3>The solution</h3>
<p>The workaround for this was the following approach:</p>
<ol>
<li>Create a private function</li>
<li>Create a function that is attached to the wrapping JavaScript object</li>
<li>Call the private function with <em>another</em> function, passed to the native AIR object&#8217;s <code>addEventListener</code> method.</li>
</ol>
<p>Using the example from above (and assuming this is within an object), here&#8217;s the code:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #003366; font-weight: bold;">var</span> self = <span style="color: #000066; font-weight: bold;">this</span>;
&nbsp;
<span style="color: #009900; font-style: italic;">// The private function</span>
<span style="color: #003366; font-weight: bold;">function</span> onIdle<span style="color: #66cc66;">&#40;</span>evt<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
    self.<span style="color: #006600;">onIdle</span><span style="color: #66cc66;">&#40;</span>evt<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #009900; font-style: italic;">// The public function</span>
<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">onIdle</span> = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>evt<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
    <span style="color: #009900; font-style: italic;">// this is an event stub that can be connected to by</span>
    <span style="color: #009900; font-style: italic;">// other objects.</span>
<span style="color: #66cc66;">&#125;</span>;
&nbsp;
<span style="color: #009900; font-style: italic;">// attach the private function to the AIR object</span>
air.<span style="color: #006600;">NativeApplication</span>.<span style="color: #006600;">nativeApplication</span>.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>air.<span style="color: #006600;">Event</span>.<span style="color: #006600;">USER_IDLE</span>, 
	onIdle<span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>The pattern is a little verbose, but now we can do something like this, elsewhere in the application:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">dojo.<span style="color: #006600;">connect</span><span style="color: #66cc66;">&#40;</span>qd.<span style="color: #006600;">app</span>, <span style="color: #3366CC;">&quot;onIdle&quot;</span>, <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>evt<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
    <span style="color: #009900; font-style: italic;">// and now we can make use of the app's onIdle event</span>
    <span style="color: #009900; font-style: italic;">// from anywhere else in Queued.</span>
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>Once we figured out this pattern, we were able to take full advantage of events fired off by AIR&#8217;s native objects using the familiar <code>dojo.connect</code> paradigm.</p>
<h2>AIR&#8217;s New Encrypted Database and the Asynchronous Connection</h2>
<p>One of the exciting new features included with AIR 1.5 is the new <a href="http://help.adobe.com/en_US/AIR/1.5/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7d29.html">encrypted SQL database</a>, based on <a href="http://sqlite.org/">the SQLite engine</a>.  We use this database to cache all of the Netflix title information that has been viewed, as well as the user&#8217;s queue information and the transaction queue (used for synchronization when returning from offline mode).  One of the neatest things about the new engine is that you can open either a synchronous or an <em>asynchronous</em> connection to the database.</p>
<p>The advantage of using an asynchronous connection is that <em>all actions performed against the database are executed on a separate thread</em>.  This means that doing some major SQL will <strong>not</strong> interrupt the thread that the user interface is run on&mdash;resulting in a faster-performing application.</p>
<h3>The Problem</h3>
<p>Aside from the complexity this introduces in code (see the <a href="http://code.google.com/p/queued/source/browse/trunk/src/js/dev/qd/services/data.js"> qd.services.data</a> object), we discovered something else&mdash;on faster machines, throwing a large number of SQL statements at the database in a short period of time would lock the database file.</p>
<p>This was particularly problematic when trying to store all of the Netflix titles that might exist in someone&#8217;s queue.  As an example, in my own account I have rented over 350 titles over the lifetime of my membership (I&#8217;ve been a Netflix member since 2003); when viewing my rental history with Queued for the first time, Queued attempts to store the information for all 350+ titles so that I can view that information offline if I want to.</p>
<h3>The Solution</h3>
<p>Since we were able to reproduce this issue consistently (some of my colleagues are avid movie watchers and have rented a <em>lot</em> of titles), the solution was to implement an internal queue of our own (oh, the irony!) within the <code>qd.services.data</code>.  We could do this because we wrapped AIR&#8217;s database access with our own, to simplify the interface and to allow for other parts of the application to <code>connect</code> to various events fired by qd.services.data.  Here&#8217;s the basic code:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #003366; font-weight: bold;">var</span> queue = <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>;
<span style="color: #003366; font-weight: bold;">function</span> exec<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> o = queue.<span style="color: #006600;">shift</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #000066; font-weight: bold;">if</span><span style="color: #66cc66;">&#40;</span>o<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
        o.<span style="color: #006600;">deferred</span>.<span style="color: #006600;">addCallback</span><span style="color: #66cc66;">&#40;</span>exec<span style="color: #66cc66;">&#41;</span>;
        o.<span style="color: #006600;">deferred</span>.<span style="color: #006600;">addErrback</span><span style="color: #66cc66;">&#40;</span>exec<span style="color: #66cc66;">&#41;</span>;
        o.<span style="color: #006600;">statement</span>.<span style="color: #006600;">execute</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>(You can see the full code <a href="http://code.google.com/p/queued/source/browse/trunk/src/js/dev/qd/services/data.js">here</a>, starting at line 238.)</p>
<p>In Queued, every query sent to the database is <em>prepared</em> with a <a href="http://docs.dojocampus.org/dojo/Deferred">dojo.Deferred</a> object; this deferred is the primary callback mechanism used throughout Queued to handle async requests.  What the above code does is search the internal queue for the next statement&mdash;and if it finds it, attaches the private <code>exec</code> function to the statement&#8217;s callback chain, ensuring that it will only execute the next statement when the previous one has completed.</p>
<p>By adding in this internal queue, we solved the database locking issues.</p>
<h2>Storing the Password for the Encrypted Database</h2>
<p>The encrypted database included with AIR requires the use of a password for opening it; you set the password when you create the database.  Because the database is encrypted using the <a href="http://en.wikipedia.org/wiki/AES_(cipher)">AES</a> cipher, the length of the password is important; it must be exactly 16 bytes long.</p>
<p>Asking a user to create this password and use it to login to Queued each time the application was run seemed a bit heavy-handed to us (especially if we needed to start padding that password to meet the 16 byte requirement), so we needed to come up with a way of dealing with this without user intervention.</p>
<h3>The solution</h3>
<p>To solve this issue, we generate a random password the first time Queued is run, like so:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #003366; font-weight: bold;">var</span> tab = <span style="color: #3366CC;">&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&amp;*&quot;</span> + 
     <span style="color: #3366CC;">&quot;~?0123456789-_abcdefghijklmnopqrstuvwxyz&quot;</span>,
     key = <span style="color: #3366CC;">&quot;&quot;</span>;
<span style="color: #000066; font-weight: bold;">for</span><span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i=<span style="color: #CC0000;">0</span>; i&lt;<span style="color: #CC0000;">16</span>; i++<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
    key += tab.<span style="color: #006600;">charAt</span><span style="color: #66cc66;">&#40;</span>Math.<span style="color: #006600;">round</span><span style="color: #66cc66;">&#40;</span>Math.<span style="color: #006600;">random</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>*tab.<span style="color: #006600;">length</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>This is not particularly robust by crypto standards, but we felt it was more than sufficient for Queued.</p>
<p>From there, we took full advantage of the <a href="http://help.adobe.com/en_US/AIR/1.5/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7e31.html">Encrypted Local Storage</a> (or ELS), also included with AIR.  This local storage is different from the encrypted database; it&#8217;s much smaller and cannot handle large amounts of data (I&#8217;ll talk about this in Part II).</p>
<p>But it is perfect for storing a password to a different data store.  So we pop this password into the storage once it&#8217;s generated.  Here&#8217;s the full code (run onLoad):</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">qd.<span style="color: #006600;">services</span>.<span style="color: #006600;">init</span> = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
    qd.<span style="color: #006600;">app</span>.<span style="color: #006600;">splash</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;Getting database password&quot;</span><span style="color: #66cc66;">&#41;</span>;
    pwd = storage.<span style="color: #000066; font-weight: bold;">item</span><span style="color: #66cc66;">&#40;</span>dbProp<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #000066; font-weight: bold;">if</span><span style="color: #66cc66;">&#40;</span>!pwd<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
        qd.<span style="color: #006600;">app</span>.<span style="color: #006600;">splash</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;Generating database password&quot;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #003366; font-weight: bold;">var</span> tab = <span style="color: #3366CC;">&quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&amp;*&quot;</span> + 
            <span style="color: #3366CC;">&quot;~?0123456789-_abcdefghijklmnopqrstuvwxyz&quot;</span>,
            key = <span style="color: #3366CC;">&quot;&quot;</span>;
        <span style="color: #000066; font-weight: bold;">for</span><span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i=<span style="color: #CC0000;">0</span>; i&lt;<span style="color: #CC0000;">16</span>; i++<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
            key += tab.<span style="color: #006600;">charAt</span><span style="color: #66cc66;">&#40;</span>Math.<span style="color: #006600;">round</span><span style="color: #66cc66;">&#40;</span>Math.<span style="color: #006600;">random</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>*tab.<span style="color: #006600;">length</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span>
        pwd = storage.<span style="color: #000066; font-weight: bold;">item</span><span style="color: #66cc66;">&#40;</span>dbProp, key<span style="color: #66cc66;">&#41;</span>;
        qd.<span style="color: #006600;">app</span>.<span style="color: #006600;">splash</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;Password generated (&quot;</span> + pwd.<span style="color: #006600;">length</span> + <span style="color: #3366CC;">&quot;)&quot;</span><span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    qd.<span style="color: #006600;">app</span>.<span style="color: #006600;">splash</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;Initializing network monitor&quot;</span><span style="color: #66cc66;">&#41;</span>;
    qd.<span style="color: #006600;">services</span>.<span style="color: #006600;">network</span>.<span style="color: #006600;">start</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    qd.<span style="color: #006600;">app</span>.<span style="color: #006600;">splash</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;Initializing database services&quot;</span><span style="color: #66cc66;">&#41;</span>;
    qd.<span style="color: #006600;">services</span>.<span style="color: #006600;">data</span>.<span style="color: #006600;">init</span><span style="color: #66cc66;">&#40;</span>pwd, db, qd.<span style="color: #006600;">services</span>._forceCreate<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>;</pre></div></div>

<p>The above code looks to the ELS for an existing password, and if it doesn&#8217;t find it it will create it and force the database services to create the database.  In this way, we&#8217;re able to take full advantage of AIR&#8217;s encrypted storage facilities without forcing user interaction.</p>
<h2>Other issues</h2>
<p>In part II of this post, I&#8217;ll talk about five other issues we ran across during the course of Queued&#8217;s development&mdash;the application sandbox, initial window placement, the ELS and performance, issues with capturing and handling the application&#8217;s exit, and the loading of icons for the tray/dock.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2009/04/01/queued-and-air-issues-part-i/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Queued: Demystifying Deferreds</title>
		<link>http://www.sitepen.com/blog/2009/03/31/queued-demystifying-deferreds/</link>
		<comments>http://www.sitepen.com/blog/2009/03/31/queued-demystifying-deferreds/#comments</comments>
		<pubDate>Tue, 31 Mar 2009 07:16:03 +0000</pubDate>
		<dc:creator>dmachi</dc:creator>
		
		<category><![CDATA[Dojo]]></category>

		<category><![CDATA[News]]></category>

		<category><![CDATA[air]]></category>

		<category><![CDATA[ajax]]></category>

		<category><![CDATA[queued]]></category>

		<category><![CDATA[Deferred]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/2009/03/31/queued-demystifying-deferreds/</guid>
		<description><![CDATA[At SitePen, we work very hard to to provide our customers and fellow developers with useful web app development services.  We&#8217;re currently deconstructing the development of Queued, our Netflix Queue management application built with Dojo and Adobe AIR.   Having presented on dojo.deferred and related topics at the Ajax Experience, and having heard [...]]]></description>
			<content:encoded><![CDATA[<p>At SitePen, we work very hard to to provide our customers and fellow developers with useful web app development services.  We&#8217;re currently deconstructing the development of Queued, our Netflix Queue management application built with Dojo and Adobe AIR.   Having presented on dojo.deferred and related topics at the Ajax Experience, and having heard that the Queued team ran into a few problems with them, I thought it would be interesting to review problems that are sometimes encountered when using Deferreds.  What is the source of these problems, are these problems related to bugs or because there are misunderstandings, and how should we address this going forward?</p>
<p>After chatting with the team for a while and looking at their use of Deferreds, I noticed a few references and grumblings to Deferred&#8217;s silent swallowing of errors. There was even a commented out section of code containing a hacked Deferred to avoid the issue.  I gathered from discussion that an error occurring NOT in the result from an XHR, but instead in its callback handler was being squelched.  After discussing this issue and realizing that there was a misunderstanding of how the callback chain worked, I decided to focus on describing the callback chain and identifying any potential bugs.</p>
<p>Callback chains created with dojo.Deferred objects provide a standardized interface for wiring an arbitrary set of actions occurring over an unknown period of time. While they are very simple to use in most common cases, the callback and errback chain is often misunderstood, and the chaining together of Deferreds themselves even more so.   A decade or so ago, I remember wanting to implement something with <a href="http://en.wikipedia.org/wiki/Pthreads">pthreads</a> to learn about the challenges I had read in using them.  I purchased a book, Programming with POSIX Threads by Larry Butenhof, and sat down to read it.  Unfortunately, I was on vacation, with no computer, and it was before I had a laptop surgically attached to my body.   So as I read, I didn&#8217;t actually do any of the examples or really understand how it all worked.  A while passed before I got to work on that again, and so I decided to read the book again this time.  For some reason, I couldn&#8217;t grasp some of the aspects around locking.  I thought and thought and thought and then I thought a couple more times for good measure.  All the authorities I had read on the subject described it as challenging.  I couldn&#8217;t figure it out just from reading this book&#8230;it truly must be hard.   As I&#8217;ve found to be the case with most things I once thought to be complicated in software development, they are often actually quite easy.</p>
<p>I sat down and wrote a couple of small programs, and within a very short period of time it just clicked.    It now seems obvious how they work and I can&#8217;t even seem to comprehend or describe why I had problems understanding it previously.   For new Dojo developers, Deferreds are a simple callback mechanism and it is pretty easy to comprehend.   When the applications become a little bit more complex or when developers try to figure out how to do a more complex behavior with their Deferreds, they then realize that there is more to understand.   Often they end up walking in my pthreads shoes or bypassing the situation altogether.</p>
<p>The common perception of dojo.Deferreds is that there are two simple chains, one for callbacks and one for errbacks, and these all get called in succession upon being triggered, much the same way that you might add a function for page launch in dojo.addOnLoad.  This in turn leads people to believe that dojo.addCallback(cb); dojo.addErrback(eb); is the same thing as dojo.addCallbacks(cb,eb).  This is NOT the case as it would be if the chain were simply two queues as is the general impression. Deferred objects in Dojo, which are directly modeled on <a href="http://twistedmatrix.com/projects/core/documentation/howto/defer.html">Twisted Python&#8217;s Deferred</a> object, contain a single queue (chain) and items are added on to the chain in <a href="http://en.wikipedia.org/wiki/Tuple">tuples</a> containing a callback and an errback.  When the deferred is triggered, it will proceed down the chain, possibly changing from &#8220;callback&#8221; to &#8220;errback&#8221; as necessary.</p>
<p><img src='http://www.sitepen.com/blog/wp-content/uploads/2009/03/deferredchaindiagram.png' alt='Deferred Chain Diagram' /></p>
<p>If callbacks are added on to the chain individually, their counterpart is filled in with null.  For example:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #003366; font-weight: bold;">var</span> def = <span style="color: #003366; font-weight: bold;">new</span> dojo.<span style="color: #006600;">Deferred</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
def.<span style="color: #006600;">addCallback</span><span style="color: #66cc66;">&#40;</span>cb<span style="color: #66cc66;">&#41;</span>;
def.<span style="color: #006600;">addErrback</span><span style="color: #66cc66;">&#40;</span>eb<span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>will result in [cb, null], [null, eb] ] being placed onto the callback chain.   On the other hand if we add to the callback chain using addCallbacks():</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #003366; font-weight: bold;">var</span> def = <span style="color: #003366; font-weight: bold;">new</span> dojo.<span style="color: #006600;">Deferred</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
def.<span style="color: #006600;">addCallbacks</span><span style="color: #66cc66;">&#40;</span>cb, eb<span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>The our resultant chain is a single item added to the stack, [cb, eb].  As you&#8217;ll notice in the diagram above, the red dotted lines moving from a callback to an errback go to the next item in the callback chain, not the peered item in the callback chain .  If a callback throws or returns an error, it will go to the next errback handler in the chain. Likewise, if an error handler returns something other than an Error object, that output will move back to the callback side of the chain. Notably,  you can continue to add onto the chain even after it has fired.  This means that when you get to the end of the chain, it just holds.  If the last callback in the chain throws an error, the Deferred will hold onto this error waiting for another errback handler to be added to the chain.  It is this last item that makes it appear to &#8220;squelch&#8221; errors that the Queued team was seeing.  However, inspection of the Deferred will show it to be sitting in an error state. Deferreds are a one-time event, but the callback chain can be added onto indefinitely.</p>
<p>Let&#8217;s take a look at some examples.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #003366; font-weight: bold;">var</span> cb = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>msg, d<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
       console.<span style="color: #006600;">log</span><span style="color: #66cc66;">&#40;</span>msg, <span style="color: #3366CC;">&quot;: &quot;</span>, d<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>;
&nbsp;
<span style="color: #003366; font-weight: bold;">var</span> def = dojo.<span style="color: #006600;">xhrGet</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span>
         url: <span style="color: #3366CC;">&quot;test.txt&quot;</span>,
         load: dojo.<span style="color: #006600;">partial</span><span style="color: #66cc66;">&#40;</span>cb, <span style="color: #3366CC;">&quot;inline callback&quot;</span><span style="color: #66cc66;">&#41;</span>,
         error: dojo.<span style="color: #006600;">partial</span><span style="color: #66cc66;">&#40;</span>cb, <span style="color: #3366CC;">&quot;inline errback&quot;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>This is a &#8216;normal&#8217; use case for the most part.  An error in the request (404 for example) will trigger the error callback.  <a href="https://user.sitepen.com/~dmachi/deferred_tests/test_inline_404.html">Run the example</a>.</p>
<p>In the following example, instead of getting an error from the IO request, we&#8217;ll use a callback with an intentional error in it, which generates an error.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #003366; font-weight: bold;">var</span> badCb = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>msg, d<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
     console.<span style="color: #006600;">log</span><span style="color: #66cc66;">&#40;</span>msg, <span style="color: #3366CC;">&quot;: &quot;</span>, d<span style="color: #66cc66;">&#41;</span>;
     badvar.<span style="color: #006600;">append</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;foo&quot;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>;
&nbsp;
<span style="color: #003366; font-weight: bold;">var</span> def = dojo.<span style="color: #006600;">xhrGet</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span>
     url: <span style="color: #3366CC;">&quot;test.txt&quot;</span>,
     load: dojo.<span style="color: #006600;">partial</span><span style="color: #66cc66;">&#40;</span>badCb, <span style="color: #3366CC;">&quot;BadCallback&quot;</span><span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>Note there is no &#8220;error&#8221; handler.  The &#8216;badCb&#8217; callback function will run and generate an error but it will be seemingly squelched.  As mentioned above, it is not actually squelched per se, but instead just waiting to be passed on to anything added onto the chain at a later point in time. <a href="https://user.sitepen.com/~dmachi/deferred_tests/test_inline_errorInCallback.html">Run the example</a>.</p>
<p>Taking this same code, but including an error handler, our error handler will catch this error to do with it as necessary (<a href="https://user.sitepen.com/~dmachi/deferred_tests/test_inline_errorInCallback_withErrorHandler.html">Example</a>).  When using the inline callbacks, they are appended to the Deferred chain in the form [loadFunc, null], [null, errorFunction].  That is, if an error occurs either as a result of the I/O operation or in the load callback, the error function will be called.   This is fine in many cases and can be exactly what you want.  With a long callback chain, however, and no error handlers or poor planning of how those error handlers are attached, it can seem as if the error was squelched.  More control can be had by adding the callbacks after creating the Deferred:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #003366; font-weight: bold;">var</span> cb = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>msg, d<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
        console.<span style="color: #006600;">log</span><span style="color: #66cc66;">&#40;</span>msg, <span style="color: #3366CC;">&quot;: &quot;</span>, d<span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span>;
&nbsp;
<span style="color: #003366; font-weight: bold;">var</span> def = dojo.<span style="color: #006600;">xhrGet</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span>
         url: <span style="color: #3366CC;">&quot;/badUrl&quot;</span>
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
def.<span style="color: #006600;">addCallbacks</span><span style="color: #66cc66;">&#40;</span>dojo.<span style="color: #006600;">partial</span><span style="color: #66cc66;">&#40;</span>cb, <span style="color: #3366CC;">&quot;[CB,eb]&quot;</span><span style="color: #66cc66;">&#41;</span>, dojo.<span style="color: #006600;">partial</span><span style="color: #66cc66;">&#40;</span>cb, <span style="color: #3366CC;">&quot;[cb,EB]&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>Our chain ends up with only a single tuple:  [cb, eb].  If an error is returned from the request itself, it will get handled by the errback handler.   On the other hand if the request is successful, but there is an error generated in the callback, it will again be seemingly (but not really!) squelched.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"> <span style="color: #003366; font-weight: bold;">var</span> cb = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>msg, d<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
       console.<span style="color: #006600;">log</span><span style="color: #66cc66;">&#40;</span>msg, <span style="color: #3366CC;">&quot;: &quot;</span>, d<span style="color: #66cc66;">&#41;</span>;
 <span style="color: #66cc66;">&#125;</span>;
&nbsp;
 <span style="color: #003366; font-weight: bold;">var</span> badCb = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>msg, d<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
       console.<span style="color: #006600;">log</span><span style="color: #66cc66;">&#40;</span>msg, <span style="color: #3366CC;">&quot;: &quot;</span>, d<span style="color: #66cc66;">&#41;</span>;
       badvar.<span style="color: #006600;">append</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;foo&quot;</span><span style="color: #66cc66;">&#41;</span>;
 <span style="color: #66cc66;">&#125;</span>;
&nbsp;
 <span style="color: #003366; font-weight: bold;">var</span> def =dojo.<span style="color: #006600;">xhrGet</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span>
      url: <span style="color: #3366CC;">&quot;test.txt&quot;</span>
 <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
 def.<span style="color: #006600;">addCallbacks</span><span style="color: #66cc66;">&#40;</span>dojo.<span style="color: #006600;">partial</span><span style="color: #66cc66;">&#40;</span>badCb, <span style="color: #3366CC;">&quot;[CB,eb]&quot;</span><span style="color: #66cc66;">&#41;</span>, dojo.<span style="color: #006600;">partial</span><span style="color: #66cc66;">&#40;</span>cb, <span style="color: #3366CC;">&quot;[cb,EB]&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>The error is waiting for another errback handler to be added to the chain.  <a href="https://user.sitepen.com/~dmachi/deferred_tests/test_addCallbacks_badCallback.html">Run the example.</a></p>
<p>As you can see, this provides insertion points so you can trigger errors and handle them in a variety of different ways.  Remember that Deferreds aren&#8217;t necessarily associated with an I/O operation.  They are simply a promise that something will happen in the future.  Just because that error happens, it doesn&#8217;t necessarily mean it is the end of the road as not all errors are fatal.   All of this can be summed up by simply stating that you have to think about how you add items on to the chain so you can insert at the desired point.   You are either adding [cb, null], [null, eb], or [cb, eb] .</p>
<p>What about a simple example of how switching states and all of this chaining can be useful.  Let&#8217;s say you are going to request a resource that may or may not exist, and if it doesn&#8217;t you want to continue using a default value.  If the errback handler is added with addErrback before the callback, this can easily be achieved.  The following example ends up with [null, eb], [cb, null] as its callback stack, so that when the &#8216;eb&#8217; function returns an onError, the deferred will then send that value to the normal callback function.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #003366; font-weight: bold;">var</span> eb = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>err<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900; font-style: italic;">/* default object */</span>  <span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">var</span> cb = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>data<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
    <span style="color: #009900; font-style: italic;">/* do something with data */</span> 
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">var</span> def = dojo.<span style="color: #006600;">xhrGet</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span>url: <span style="color: #3366CC;">&quot;/fubar&quot;</span><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #009900; font-style: italic;">// add the errorback function first, [null, eb], </span>
<span style="color: #009900; font-style: italic;">// so that if the xhr has an error it can catch it </span>
<span style="color: #009900; font-style: italic;">// and still be able to continue to the normal chain</span>
def.<span style="color: #006600;">addErrback</span><span style="color: #66cc66;">&#40;</span>eb<span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #009900; font-style: italic;">// this chain will process either a successful return </span>
<span style="color: #009900; font-style: italic;">// from xhrGet OR the result of the errback handler</span>
def.<span style="color: #006600;">addCallback</span><span style="color: #66cc66;">&#40;</span>cb<span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>Now you may be thinking that this implies you have to always end with an errback or the deferred will seem to squelch the error.  This makes it difficult to add an arbitrary number of callback items and ensure an errback is added last to catch any problems.   It is the understanding of how Deferreds themselves can be chained together that puts everything into perspective.</p>
<p>Dojo developers often think of Deferreds at the level of I/O, but they are much more useful than that when well thought out.  Let&#8217;s create an example.   On our page we want to have a simple startup system  that does a number of different startup tasks.  For our init method, we want to initialize the communication system, and then show the user interface.  However, the initComms() section can be broken down into getting the data, processing the data, and then sending off a message.  By chaining deferred objects together (as opposed to adding a function onto a particular Deferred&#8217;s callback chain), complex procedures can be broken down into simple tasks, and error handling can be handled at any level or bubble up to the outermost Deferred.  To chain two Deferreds together, simply add a function that will return a Deferred to another Deferred&#8217;s callback chain!  For example:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #003366; font-weight: bold;">var</span>  def = <span style="color: #003366; font-weight: bold;">new</span> dojo.<span style="color: #006600;">Deferred</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
def.<span style="color: #006600;">addCallback</span><span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
     <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">new</span> dojo.<span style="color: #006600;">Deferred</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>In this example, we are adding a function that returns a Deferred object.  The outer Deferred will trigger the launch of the inner Deferred&#8217;s process, and will block any more callbacks until the inner has exhausted is entire callback chain.  Diving right into the details, here is an <a href="https://user.sitepen.com/~dmachi/deferred_tests/test_chaining.html">example</a>.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript"><span style="color: #009900; font-style: italic;">// Init comms function.  This will call getData() which</span>
<span style="color: #009900; font-style: italic;">// returns a deferred representing the process of retrieving data</span>
<span style="color: #009900; font-style: italic;">// and processing it.  After getData() is complete, </span>
<span style="color: #009900; font-style: italic;">// send a message to the server, and then log completed.</span>
&nbsp;
initComms = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
       <span style="color: #009900; font-style: italic;">//getData returns a deferred</span>
       <span style="color: #003366; font-weight: bold;">var</span> initDeferred = getData<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
       <span style="color: #009900; font-style: italic;">// add sendMessage to the chain.</span>
       initDeferred.<span style="color: #006600;">addCallback</span><span style="color: #66cc66;">&#40;</span>sendMessage<span style="color: #66cc66;">&#41;</span>;
&nbsp;
       <span style="color: #009900; font-style: italic;">// log this as completed</span>
       initDeferred.<span style="color: #006600;">addCallback</span><span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
               console.<span style="color: #006600;">log</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;initComms Completed&quot;</span><span style="color: #66cc66;">&#41;</span>;
       <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
       <span style="color: #000066; font-weight: bold;">return</span> initDeferred;
 <span style="color: #66cc66;">&#125;</span>
&nbsp;
 getData = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
        <span style="color: #009900; font-style: italic;">// Request data from the server</span>
        console.<span style="color: #006600;">log</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;getData()&quot;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #003366; font-weight: bold;">var</span> def = dojo.<span style="color: #006600;">xhrGet</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span>
               url: <span style="color: #3366CC;">&quot;test.txt&quot;</span>
        <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #009900; font-style: italic;">// process it in some fashion, or if there was an xhr error</span>
        <span style="color: #009900; font-style: italic;">// throw the error handler</span>
        def.<span style="color: #006600;">addCallback</span><span style="color: #66cc66;">&#40;</span>processData<span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #009900; font-style: italic;">// log that we are finished</span>
        def.<span style="color: #006600;">addCallback</span><span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
              console.<span style="color: #006600;">log</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;Get Data Complete&quot;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #009900; font-style: italic;">//return the deferred from the initial xhr</span>
        <span style="color: #000066; font-weight: bold;">return</span> def;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #009900; font-style: italic;">// dummy process data func</span>
processData = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>d<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
        <span style="color: #009900; font-style: italic;">/* do something */</span>
        console.<span style="color: #006600;">log</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;Process Data: &quot;</span>, d<span style="color: #66cc66;">&#41;</span>;
        <span style="color: #000066; font-weight: bold;">return</span> d; <span style="color: #009900; font-style: italic;">/* return processed data */</span>
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #009900; font-style: italic;">// dummy send message func</span>
sendMessage = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>msg<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
        dojo.<span style="color: #006600;">publish</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;/msg&quot;</span>, <span style="color: #66cc66;">&#91;</span>msg<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span>;
        console.<span style="color: #006600;">log</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;Sent Message&quot;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #000066; font-weight: bold;">return</span> msg;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #009900; font-style: italic;">// showUi creates a new dojo.deferred, adds a log </span>
<span style="color: #009900; font-style: italic;">// message callback, and then returns</span>
<span style="color: #009900; font-style: italic;">// The setTimeout() call is used to represent the </span>
<span style="color: #009900; font-style: italic;">// work that might go on in this function</span>
showUi = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
        console.<span style="color: #006600;">log</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;showUi&quot;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #003366; font-weight: bold;">var</span> def = <span style="color: #003366; font-weight: bold;">new</span> dojo.<span style="color: #006600;">Deferred</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
        def.<span style="color: #006600;">addCallback</span><span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
               console.<span style="color: #006600;">log</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;showUI completed&quot;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
        <span style="color: #009900; font-style: italic;">// for demo, trigger the showUi work with a trigger</span>
        setTimeout<span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>def.<span style="color: #006600;">callback</span><span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">true</span><span style="color: #66cc66;">&#41;</span>;<span style="color: #66cc66;">&#125;</span>, <span style="color: #CC0000;">50</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #000066; font-weight: bold;">return</span> def;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
<span style="color: #009900; font-style: italic;">// &quot;Main&quot;</span>
&nbsp;
<span style="color: #009900; font-style: italic;">// call initComms and get a deferred back for the whole process</span>
<span style="color: #003366; font-weight: bold;">var</span> initDef = initComms<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #009900; font-style: italic;">// add showUI to the callback chain.  showUI returns a deferred object, whose</span>
<span style="color: #009900; font-style: italic;">// process will be kicked off here</span>
&nbsp;
initDef.<span style="color: #006600;">addCallback</span><span style="color: #66cc66;">&#40;</span>showUi<span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #009900; font-style: italic;">// this will not be executed until the Deferred returned from showUi </span>
<span style="color: #009900; font-style: italic;">// and all its callbacks have been completed.  We didn't add any </span>
<span style="color: #009900; font-style: italic;">// error handling in the individual functions, though we could have,</span>
<span style="color: #009900; font-style: italic;">// and instead let the error bubble up to the outermost Deferred.</span>
&nbsp;
initDef.<span style="color: #006600;">addCallbacks</span><span style="color: #66cc66;">&#40;</span>
        <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
              console.<span style="color: #006600;">log</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;READY&quot;</span><span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span>,
        <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>err<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
              console.<span style="color: #006600;">warn</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;ERROR Starting APP: &quot;</span>, err<span style="color: #66cc66;">&#41;</span>;
        <span style="color: #66cc66;">&#125;</span>    
<span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>Deferreds can be both powerful and simple.  After having gone through the exercise of testing each of these scenarios and making sure that they fit the original Twisted specification, I do not believe that there is a bug here, only a misunderstanding of the errback chain.  I believe that Deferreds provide a powerful and elegant way to work with asynchronous events, but at the same time they can be difficult to follow.  </p>
<p>While I personally prefer using the Deferreds, many people don&#8217;t use this power and in some cases are befuddled by its behavior.  Some are of the opinion that they are too complicated and shouldn&#8217;t be used for things like XHRs in Dojo going forward.  What does the Dojo developer community think about the future of Deferreds for Dojo 2.x?  Should we be looking at getting rid of Deferreds in Dojo? Should we simplify this into two simple queues?  What&#8217;s your opinion?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2009/03/31/queued-demystifying-deferreds/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Queued: Architectural Decisions</title>
		<link>http://www.sitepen.com/blog/2009/03/30/architecting-queued/</link>
		<comments>http://www.sitepen.com/blog/2009/03/30/architecting-queued/#comments</comments>
		<pubDate>Mon, 30 Mar 2009 07:07:08 +0000</pubDate>
		<dc:creator>Revin</dc:creator>
		
		<category><![CDATA[Dojo]]></category>

		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[Open Source]]></category>

		<category><![CDATA[air]]></category>

		<category><![CDATA[ajax]]></category>

		<category><![CDATA[css]]></category>

		<category><![CDATA[offline]]></category>

		<category><![CDATA[queued]]></category>

		<guid isPermaLink="false">http://www.sitepen.com/blog/2009/03/30/architecting-queued/</guid>
		<description><![CDATA[Dojo is a very flexible toolkit; it doesn&#8217;t dictate how you organize your code or create your widgets. It simply provides tools, and it&#8217;s up to you to decide how you want to fit them together. Developing with AIR puts you squarely in the browser-based application model, but aside from that it mostly stays out [...]]]></description>
			<content:encoded><![CDATA[<p>Dojo is a very flexible toolkit; it doesn&#8217;t dictate how you organize your code or create your widgets. It simply provides tools, and it&#8217;s up to you to decide how you want to fit them together. Developing with AIR puts you squarely in the browser-based application model, but aside from that it mostly stays out of your way as well. As part of our series on the Queued development process, I&#8217;m going to take a look at the decisions we made and the philosophies we adopted for the project. It should provide some insight into our process.</p>
<h2>Deciding on Functionality</h2>
<p>Certain requirements were set in stone from the beginning. We had to use AIR&#8217;s database. We had to do an offline mode. We had to support a mode where Queued could run in the background. We had to demonstrate a tight Dojo build. We had to support drag and drop for queue re-ordering&mdash;stuff like that. Other things were optional; for example, we <em>could</em> demonstrate the Encrypted Local Store (ELS), but it wasn&#8217;t a blocker. After that, though, it was pretty wide open, so we had to decide how much to bite off and still be able to meet our deadlines.</p>
<h3>To Be, or Not to Be (Multi-User)?</h3>
<p>We did a lot of work around the user model. Should we support multiple accounts? That seems like an obvious feature to include, and as web application developers, we work with user authentication all the time. So, we prototyped a model where the application would store separate user credentials in the ELS and use those to authenticate with Netflix. Here are a few screenshots of the designs we went through:</p>
<p style="text-align:center;">
<img src='http://www.sitepen.com/blog/wp-content/uploads/2009/03/login-dialog.jpg' alt='Queued alpha login dialog'/><br />
<img src='http://www.sitepen.com/blog/wp-content/uploads/2009/03/login-integrated.jpg' alt='Queued alpha login redux' />
</p>
<p>And after the <em>Less Red</em> Redesign that Torrey talked about in a previous post:</p>
<p style="text-align:center;">
<img src='http://www.sitepen.com/blog/wp-content/uploads/2009/03/login-blue.jpg' alt='Queued alpha login, attempt 3' /><br />
<img src='http://www.sitepen.com/blog/wp-content/uploads/2009/03/login-blue-password.jpg' alt='Queued alpha login, attempt 3 (password entry)' />
</p>
<h3>Integrating the Pieces</h3>
<p>Quite a few of Queued&#8217;s internals were still in the prototype stage at this point, and right about here was where the OAuth code started getting put in place. This presented us with a challenge. As a team, we&#8217;re so used to the web application authentication model&mdash;where authentication happens on some remote server&mdash;that we were automatically falling into that paradigm almost out of habit. It&#8217;s just the way our projects tend to work. However, Queued is essentially a desktop application, so that model doesn&#8217;t necessarily fit.</p>
<p>We had originally assumed we&#8217;d be able to store sets of login credentials in the ELS and use those at application startup to authenticate with the Netflix API and get rolling. However, Netflix uses the <a href="http://oauth.net/">OAuth protocol</a>, and OAuth fundamentally doesn&#8217;t work that way.</p>
<p>Traditional username/password-based authentication is like showing your ID to get into, say, a bar. You come and go as you please, but if you leave for long enough, be prepared to flash your ID again to get back in. OAuth, on the other hand, is like having your hand stamped when you enter an amusement park: if you leave, the stamp gets you back in. In this case, the stamp is a token you use to sign your API calls, and Queued gets this token after redirecting you to netflix.com so you can authorize the application to access your account. So, <strong><em>Queued never knows your Netflix login credentials at any time.</em></strong>. This is how OAuth is designed, and it has its benefits, but it didn&#8217;t really work with our defined interaction/login model.</p>
<h3>Decision Time</h3>
<p>We had to make a difficult decision: cut multi-user capability for the 1.0 release. We feel this decision made sense, not only because of the deadline constraints, but because by default, AIR provides different databases and ELS for each operating system user, and we <em>were</em> building a desktop application, after all. We decided to follow that model, and since that&#8217;s what AIR expects, the entire toolchain would inherently support that mode of operation.</p>
<p>In the final 1.0 release, therefore, you won&#8217;t find any login screens, but you <em>will</em> find a button that kicks off the OAuth handshake:</p>
<p style="text-align:center;">
<img src='http://www.sitepen.com/blog/wp-content/uploads/2009/03/login-oauth.jpg' alt='Queued OAuth-based authentication' />
</p>
<p>It was tough to say goodbye to multi-user capability, but in the end, it let us focus on our core requirements, so in retrospect, it was probably the right decision to make under the circumstances. <a href="http://code.google.com/p/queued/">Queued is Open Source</a>, of course, so don&#8217;t feel like you have to wait on us if you want that implemented; aside from the necessary UI work, Queued&#8217;s internals are mostly set up so they don&#8217;t care whether the app is single-user or multi-user. Have at it :-)</p>
<p>That&#8217;s one example of the kind of iterative process we use. Let&#8217;s talk architecture.</p>
<h2>Deciding on Architecture</h2>
<p>Getting a new Dojo-based project started can sometimes be daunting, precisely <em>because</em> it doesn&#8217;t force a particular structure on you. The field is wide open. Our first task was to start putting <a href="/labs/dair/">dAIR</a>-based tests together to figure out how we should handle things like window initialization and database access. While that was happening, we had to figure out how to organize our assets and divide up responsibility within the team. We landed on a few key things&mdash;nothing really new, but certainly, choices that we could have easily taken in a different direction.</p>
<h3>Do as much as possible in CSS.</h3>
<p>Dojo&#8217;s widget toolkit, Dijit, is robust. You get i18n &amp; a11y out of the box, for example. However, those were outside the scope of this project, which was to be a small fast technology demo. One specific requirement was to keep the built .air package as small as possible, so we made the choice to cut everything that didn&#8217;t directly contribute to our project requirements. Since we were dealing with a single WebKit-based engine and didn&#8217;t need all of the great cross-engine compatibility stuff in Dijit, and since CSS is generally faster than JavaScript for just about anything that CSS can do, our simple rule was that if you can do something in CSS, you do it in CSS. Even if it took JavaScript code to trigger a change, we pushed as much of the change as possible into the stylesheet. This means, for example, that we created a lot of CSS classes to define state (stuff like &#8220;.movie.inQueue&#8221;) rather than changing node styles individually.</p>
<p>If you read through the code in the <a href="http://code.google.com/p/queued/source/browse/">repository</a>, you&#8217;ll certainly find some Dijit, but it&#8217;s mostly restricted to the <a href="http://code.google.com/p/queued/source/browse/trunk/src/js/dev/qd/init.js">initial interface layout</a> (BorderContainer and friends).</p>
<h3>Stick with Unobtrusive JavaScript.</h3>
<p>Most people advocate the concept of Unobtrusive JavaScript, for a variety of reasons. For Queued, we didn&#8217;t have to worry about SEO, making sure our tags were semantic, or any of the big philosophical ideas of Correctness. In an app like this, HTML simply acts as a UI spec. What it came down to for us was separation of design and behavior. It allowed our CSS pros to work their magic on as sparse a DOM as we could provide, without distraction by things like inline event handlers. There was probably a tiny performance benefit to not including the Dojo parser and working through the DOM looking for dojoType attributes and instantiating widgets in markup, but that&#8217;s just a nice side effect.</p>
<p>Initializing widgets in this style usually means running some code with <code>dojo.addOnLoad</code>, selecting nodes with <code>dojo.query</code> or <code>dojo.byId</code>, and attaching event handlers to them with <code>dojo.connect</code>. The <code>dojo.behavior</code> module is a great way to do this <em>en masse</em>. We ended up structuring our application code where most modules followed a pattern like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">dojo.<span style="color: #006600;">provide</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;qd.app.someModule&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
dojo.<span style="color: #006600;">require</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;dojo.behavior&quot;</span><span style="color: #66cc66;">&#41;</span>;
dojo.<span style="color: #006600;">require</span><span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;qd.app&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
qd.<span style="color: #006600;">app</span>.<span style="color: #006600;">someModule</span> = <span style="color: #003366; font-weight: bold;">new</span> <span style="color: #66cc66;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
	<span style="color: #009900; font-style: italic;">// private variables</span>
	<span style="color: #003366; font-weight: bold;">var</span> foo = <span style="color: #003366; font-weight: bold;">null</span>,
	    bar = <span style="color: #003366; font-weight: bold;">null</span>,
	    thinger = <span style="color: #003366; font-weight: bold;">null</span>;
&nbsp;
	<span style="color: #003366; font-weight: bold;">function</span> privateMethod<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
		<span style="color: #009900; font-style: italic;">// code here</span>
	<span style="color: #66cc66;">&#125;</span>
&nbsp;
	<span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #006600;">publicMethod</span> = <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
		<span style="color: #009900; font-style: italic;">// code here</span>
	<span style="color: #66cc66;">&#125;</span>;
&nbsp;
	<span style="color: #009900; font-style: italic;">// this module's behaviors</span>
	dojo.<span style="color: #006600;">behavior</span>.<span style="color: #006600;">add</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#123;</span>
		<span style="color: #3366CC;">&quot;.someSelector .someOtherOne&quot;</span>:<span style="color: #66cc66;">&#123;</span>
			onmouseover:<span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>e<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
				<span style="color: #009900; font-style: italic;">// code here</span>
			<span style="color: #66cc66;">&#125;</span>,
			onclick:<span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>e<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
				<span style="color: #009900; font-style: italic;">// code here</span>
			<span style="color: #66cc66;">&#125;</span>
		<span style="color: #66cc66;">&#125;</span>,
		<span style="color: #3366CC;">&quot;#oneParticularNode .childNode img.thinger&quot;</span>:<span style="color: #66cc66;">&#123;</span>
			onclick:<span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span>e<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
				<span style="color: #009900; font-style: italic;">// code here</span>
			<span style="color: #66cc66;">&#125;</span>
		<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>To use this code in the application, we simply do <code>dojo.require("qd.app.someModule")</code> in the initialization code; the closure gets put together immediately, and the module gets itself all set up.</p>
<p>Being closure-bound like this, each module now had &#8220;private&#8221; and &#8220;public&#8221; members, and we could use <code>dojo.behavior</code> in each module to provide that module&#8217;s behaviors. Used this way, <code>dojo.behavior</code> will do a bunch of <code>dojo.query</code>/<code>dojo.connect</code> sequences for us; the syntax is more direct than doing them all manually, so it makes for more readable code.</p>
<p>JSLint doesn&#8217;t particularly like the <code>someModule = new (function(){ ... })()</code> idiom, however. It always complains, &#8220;weird construction. Delete &#8216;new&#8217;&#8221;, but it&#8217;s a perfectly valid way to create singleton modules, so we stuck with it.</p>
<p>As an example, you may want to look at <a href="http://code.google.com/p/queued/source/browse/trunk/src/js/dev/qd/app/tooltip.js">tooltip.js</a>, which is the module that creates the movie hover info toolip. It&#8217;s fully self-contained, without a single public member. Also, try <a href="http://code.google.com/p/queued/source/browse/trunk/src/js/dev/qd/app/ratings.js">ratings.js</a>, which builds the star rating widgets. Those are good examples of the code structure I&#8217;m talking about.</p>
<h3>Abstract functionality into internal services.</h3>
<p>Finally, even though there isn&#8217;t necessarily the concept of a server-side and a client-side in this kind of application, we decided to organize certain things as though there was, by creating various &#8220;services&#8221; to act as data sources to the application. They&#8217;re the middle layer between the application and AIR system-level stuff like the database or ELS or external data like the Netflix API. For example, we created a service to parse Netflix&#8217;s XML, a service to handle authentication, and a few others. To the rest of the application, those act as an internal API that abstracts the lower-level details away and keeps the app code focused on the interaction of our objects.</p>
<p>The biggest place where this structure helped was in creating the offline mode. One of our modules continually monitors network availability and stores the status in <code>qd.services.network.available</code>. The rest of the application will automatically toggle between online and offline modes because of this simple bit of code:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript">qd.__defineGetter__<span style="color: #66cc66;">&#40;</span><span style="color: #3366CC;">&quot;service&quot;</span>, <span style="color: #003366; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span>
	<span style="color: #009900; font-style: italic;">//	summary:</span>
	<span style="color: #009900; font-style: italic;">//		Return the proper service (qd.services.online, qd.services.offline)</span>
	<span style="color: #009900; font-style: italic;">//		based on the current network status.</span>
	<span style="color: #003366; font-weight: bold;">var</span> b = qd.<span style="color: #006600;">services</span>.<span style="color: #006600;">network</span>.<span style="color: #006600;">available</span>;
	<span style="color: #000066; font-weight: bold;">return</span> b ? qd.<span style="color: #006600;">services</span>.<span style="color: #006600;">online</span> : qd.<span style="color: #006600;">services</span>.<span style="color: #006600;">offline</span>;	<span style="color: #009900; font-style: italic;">//	Object</span>
<span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>That&#8217;s it! This getter transparently (to the caller) switches between the Netflix API and the local database cache as network availability varies, so calling <code>qd.service.titles.find(...)</code>, for example, will search for titles using the best available source automatically. The calling code doesn&#8217;t need to figure that out for itself.</p>
<h2>Check it Out</h2>
<p><a href="/labs/queued/">Queued</a> lives in <a href="/labs/">SitePen Labs</a>, so check that out if you haven&#8217;t already. The latest code is hosted at <a href="http://code.google.com/p/queued/">Google Code</a>. Check back soon for more in our Queued series.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sitepen.com/blog/2009/03/30/architecting-queued/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
