<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Enterprise Dojo</title>
	<atom:link href="http://www.enterprisedojo.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.enterprisedojo.com</link>
	<description>Serious Frontend Development For Us Cubicle Dwellers</description>
	<lastBuildDate>Fri, 14 Oct 2011 04:01:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Coast to Coast with dojo.string.substitute</title>
		<link>http://www.enterprisedojo.com/2011/10/14/coast-to-coast-with-dojo-string-substitute/</link>
		<comments>http://www.enterprisedojo.com/2011/10/14/coast-to-coast-with-dojo-string-substitute/#comments</comments>
		<pubDate>Fri, 14 Oct 2011 04:01:14 +0000</pubDate>
		<dc:creator>Dan Lee</dc:creator>
				<category><![CDATA[Dojo]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[dojo]]></category>
		<category><![CDATA[dojo.string.substitute]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.enterprisedojo.com/?p=1539</guid>
		<description><![CDATA[Have you ever written JavaScript that injects values into the middle of a string? Did you <code>slice</code>, <code>substring</code>, and <code>RegExp</code> your way to victory? You probably did. Unless great care is taken, this approach is fragile and produces code that is almost certainly difficult to read. Dojo provides help for this problem via an incredibly convenient utility for performing parametrized substitutions on a string, <a target="_blank" href="http://dojotoolkit.org/api/1.6/dojo/string/substitute">dojo.string.substitute</a>.]]></description>
			<content:encoded><![CDATA[<p>I recently relocated from Raleigh, North Carolina to San Francisco, California. My beautiful and ridiculously talented partner of 9 years got a job in Sausalito, and we took the plunge. The moving process involved a cross-country drive that took roughly five days to complete. Here&#8217;s an action shot of me driving through Montana, accompanied by my heavily sedated cat, Frenzy.</p>
<p>&nbsp;</p>
<p><center><img class="aligncenter size-full wp-image-1540" title="sedatedFrenzy" src="http://www.enterprisedojo.com/wp-content/uploads/2011/10/sedatedFrenzy.jpg" alt="" width="450" height="338" />&nbsp;</center></p>
<p>I&#8217;ve been in San Francisco for about a week now. I know this shouldn&#8217;t have come as a surprise, but let me state the obvious. <strong>San Francisco is different than Raleigh.</strong> HTML5 should include a &lt;DUH&gt; element for assertions like that, but I must say, I did not fully prepare myself for the lifestyle changes associated with such a move. It&#8217;s like my life has been passed through a series of 1-to-1 substitutions. Let me see if I can illustrate this through a series of examples, showing off one of my favorite Dojo utilities: dojo.string.substitute.</p>
<h2>Substitutions</h2>
<p>Have you ever written JavaScript that injects values into the middle of a string? Did you <code>slice</code>, <code>substring</code>, and <code>RegExp</code> your way to victory? You probably did. Unless great care is taken, this approach is fragile and produces code that is difficult to read. Dojo helps solve this problem via an incredibly convenient utility for performing parametrized substitutions on a string, <a target="_blank" href="http://dojotoolkit.org/api/1.6/dojo/string/substitute">dojo.string.substitute</a>. Let&#8217;s look at a quick example.</p>
<p>In this form, <code>dojo.string.substitute</code> allows you to pass it a string with numbered parameters, and an array whose indices correspond to those parameters. </p>
<p>(In all of the subsequent examples, be sure to <code>dojo.require("dojo.string")</code> to gain access to the substitute function).</p>
<pre class="brush: jscript; title: ; notranslate">
var template = &quot;In ${0}, Sweet Tea is ${1}&quot;;

var raleigh = dojo.string.substitute(template,
    [&quot;Raleigh&quot;,
    &quot;abundant and plentiful.&quot;]),

var sf = dojo.string.substitute(template,
    [&quot;San Francisco&quot;,
    &quot;no where to be found. I'm pretty sure it is illegal.&quot;]);

console.log(raleigh);
console.log(sf);
</pre>
<h3>Output</h3>
<pre class="brush: plain; title: ; notranslate">
In Raleigh, Sweet Tea is abundant and plentiful.

In San Francisco, Sweet Tea is no where to be found. I'm
pretty sure it is illegal.
</pre>
<h2>Objects as Variables</h2>
<p>The second argument to <code>dojo.string.substitute</code> can also be an object. In this case, the variables in the template correspond to the property names of the supplied object. </p>
<pre class="brush: jscript; title: ; notranslate">
var template = &quot;Autumn clothing layers for ${city}: ${clothingList}&quot;;

var raleigh = dojo.string.substitute(template,
    { city: &quot;Raleigh&quot;, clothingList: &quot;Hoodie, T-Shirt, Pants&quot; });

var sf = dojo.string.substitute(template,
    { city:&quot;San Francisco&quot;, clothingList: &quot;Rain Coat, Coat, Puffy Vest, Hoodie, Long-Sleeve T-Shirt, Short-Sleeve T-Shirt, Pants, Shorts, Speedo (Optional, but better to be safe)&quot;});

console.log(raleigh);
console.log(sf);
</pre>
<h3>Output</h3>
<pre class="brush: plain; title: ; notranslate">
Autumn clothing layers for Raleigh: Hoodie, T-Shirt, Pants

Autumn clothing layers for San Francisco: Rain Coat,
Coat, Puffy Vest, Hoodie, Long-Sleeve T-Shirt,
Short-Sleeve T-Shirt, Pants, Shorts,
Speedo (Optional, but better to be safe)
</pre>
<h2>Nested Objects</h2>
<p>When using objects to specify variable values, it is not necessary to use top-level properties. You can use plain ol&#8217; JavaScript dot notation to specify properties nested within objects.</p>
<pre class="brush: jscript; title: ; notranslate">
var template =
    &quot;Number of naked people I saw in public in ${nakedPeopleDesc.city}: ${nakedPeopleDesc.count}.&quot;;

var raleigh = dojo.string.substitute(template,
{
    nakedPeopleDesc:
        {
          city: &quot;Raleigh&quot;,
          count: &quot;Zero&quot;
        }
});

var sf = dojo.string.substitute(template,
{
    nakedPeopleDesc:
        {
            city: &quot;San Francisco&quot;,
            count: &quot;Four. And that was just this morning&quot;
        }
});

console.log(raleigh);
console.log(sf);
</pre>
<h3>Output</h3>
<pre class="brush: plain; title: ; notranslate">
Number of naked people I saw in public in Raleigh: Zero.

Number of naked people I saw in public in San Francisco: Four.
And that was just this morning.
</pre>
<h2>Your friend in i18n</h2>
<p>Probably the most useful case for <code>dojo.string.substitute</code> is when specifying externalized strings in your i18n bundles. (If you aren&#8217;t familar with internationalization in Dojo, see my <a href="http://www.enterprisedojo.com/2010/11/22/from-springfield-to-stuttgart-an-introduction-to-i18n-with-dojo/" title="i18n with Dojo" target="_blank">article on the subject</a>).  Let&#8217;s say you have something like this. This function returns a string to display a greeting to a user, informing them of their unread messages count.</p>
<pre class="brush: jscript; title: ; notranslate">
function getGreeting(nameOfPerson, unreadCount) {
   return &quot;Hello, &quot; + nameOfPerson + &quot;. You have &quot; +
        unreadCount + &quot; unread messages.&quot;;
}
</pre>
<p>When it comes time to externalize the string returned by the above function, how would you go about doing it? One option is to slice it up into multiple strings and add each string as an entry in your i18n bundle. That will work fine for English, but what about other languages? I&#8217;m no linguist, but I bet there are languages where <code>unreadCount</code> will make more sense in a different context than in between &#8220;You have&#8221; and &#8220;unread messages&#8221;. You are making the lives of your translation team more difficult by adopting this slice n&#8217; dice strategy.  The translator will have to first recognize that your multiple strings are part of the same message, and then heroically mash them into something that makes sense. Translators are a clever bunch, and they will figure it out, but why put them through the trouble? The more elegant solution to this problem is to externalize a template like this:</p>
<pre class="brush: jscript; title: ; notranslate">
&quot;Hello, ${nameOfPerson}. You have ${unreadCount} unread messages.&quot;
</pre>
<p>Now your translators have a single string to work with, and it&#8217;s a much easier task to rearrange that string in a manner that makes sense for a specific language. <a href="http://www.ibm.com/developerworks/web/library/wa-dojo/" target="_blank">This article on developerWorks</a> demonstrates an example of how to create a mixin that automatically delegates to <code>dojo.string.substitute</code>. Cool stuff, definitely worth a read.</p>
<h2>Conclusion</h2>
<p><code>dojo.string.substitute</code> isn&#8217;t an earth-shattering API, but used effectively, it can clean up some of the less-than-beautiful string manipulation lurking in your codebase.  And in an i18n context, it is absolutely essential. </p>
<p>Wish me luck in San Francisco; I&#8217;m doing a decent job of adjusting. Oh, except for one thing. Did you know that NFL games start at 10:00am out here?! That&#8217;s just silly.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.enterprisedojo.com/2011/10/14/coast-to-coast-with-dojo-string-substitute/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Building Neat Stuff with Dojo and YQL</title>
		<link>http://www.enterprisedojo.com/2011/07/21/building-neat-stuff-with-dojo-and-yql/</link>
		<comments>http://www.enterprisedojo.com/2011/07/21/building-neat-stuff-with-dojo-and-yql/#comments</comments>
		<pubDate>Thu, 21 Jul 2011 22:24:22 +0000</pubDate>
		<dc:creator>Dan Lee</dc:creator>
				<category><![CDATA[Dojo]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[dojo]]></category>
		<category><![CDATA[yql]]></category>

		<guid isPermaLink="false">http://www.enterprisedojo.com/?p=1416</guid>
		<description><![CDATA[I'm in love with <a target="_blank" href="http://developer.yahoo.com/yql/">YQL</a>. Never heard of it? I'm not surprised. To borrow a term from the hip-hop community, YQL is probably the most <a target="_blank" href="http://www.urbandictionary.com/define.php?term=slept+on">slept-on</a> technology in the field of Front End Engineering. In a nutshell, YQL lets you query for interesting data that can be easily consumed by a web app. In this article, I'll show you how to dynamically inject data from YQL queries into your apps using Dojo.]]></description>
			<content:encoded><![CDATA[<link rel="stylesheet" type="text/css" href="/postresources/yqlDemo/yqldemo.css" />
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js" type="text/javascript"></script><br />
<script src="/postresources/yqlDemo/yqldemo.js" type="text/javascript"></script><br />
I&#8217;m in love with <a target="_blank" href="http://developer.yahoo.com/yql/">YQL</a>. Never heard of it? I&#8217;m not surprised. To borrow a term from the hip-hop community, YQL is probably the most <a target="_blank" href="http://www.urbandictionary.com/define.php?term=slept+on">slept-on</a> technology in the field of web development.  YQL is defined by Yahoo! as: &#8216;an expressive SQL-like language that lets you query, filter, and join data across Web services.&#8217; In a nutshell, YQL lets you query for interesting data that can be easily consumed by a web app. The best way to understand what YQL is about is to play around with the <a target="_blank" href="http://developer.yahoo.com/yql/console/">YQL Console</a>. Be sure to click the &#8216;Show Community Tables&#8217; Link in the right sidebar to reveal all of the data sources. Look at this stuff! Want to find favorably reviewed sushi restaurants in San Francisco? <a target="_blank" href="http://developer.yahoo.com/yql/console/?q=show%20tables&#038;env=store://datatables.org/alltableswithkeys#h=select%20*%20from%20local.search%20where%20query%3D%22sushi%22%20and%20location%3D%22san%20francisco%2C%20ca%22%20and%20Rating.AverageRating%3D%224.5%22">Here ya go</a>.  (Click the &#8216;Test&#8217; button to fetch the data). How about the most recent Tweets with the <a target="_blank" href="http://developer.yahoo.com/yql/console/?q=show%20tables&#038;env=store://datatables.org/alltableswithkeys#h=select%20*%20from%20twitter.search%20where%20q%3D%27%23dojo%27%3B">#dojo hashtag</a>?  Neat, yes?</p>
<h2>Getting YQL Data Into Your Page</h2>
<p>The coolest thing about YQL is how easy it is to get this great data into your app. Historically speaking it has been a pain to do mashup style apps with JavaScript due to the fact that browsers make it all-but-impossible to invoke AJAX requests across domain boundaries. YQL uses a clever technique known as <a target="_blank" href="http://en.wikipedia.org/wiki/JSONP">JSON-P</a> to work-around these cross-domain restrictions.  JSON-P utilizes the fact that browsers <strong>do</strong> allow <code>src</code> attributes of script elements to be cross-domain. Thus it&#8217;s perfectly fine to include a script element with a Yahoo! domain in your page. Here is what that looks like for the Twitter query that I linked to earlier.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;script type=&quot;text/javascript&quot;
src=&quot;http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20twitter.search%20where%20q%3D'%23dojo'%3B&amp;format=json&amp;diagnostics=true&amp;env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&amp;callback=cbfunc&quot;&gt;&lt;/script&gt;
</pre>
<p>The JavaScript that the above script element returns to us consists entirely of a block of JSON data wrapped in a function invocation: </p>
<pre class="brush: jscript; title: ; notranslate">
cbfunc({
 ...
  &quot;results&quot;: {
   &quot;results&quot;: [
    {
     &quot;to_user_id&quot;: &quot;null&quot;,
     &quot;text&quot;: &quot;Understanding Widget - The dojo toolkit http://ow.ly/5kMmW #dojo&quot;,
     &quot;id&quot;: &quot;82046157043408896&quot;,
     &quot;from_user_id&quot;: &quot;2632678&quot;,
     &quot;geo&quot;: &quot;null&quot;,
     &quot;iso_language_code&quot;: &quot;en&quot;,
     &quot;to_user_id_str&quot;: &quot;null&quot;,
     &quot;source&quot;: &quot;&amp;lt;a href=&amp;quot;http://www.hootsuite.com&amp;quot; rel=&amp;quot;nofollow&amp;quot;&amp;gt;HootSuite&amp;lt;/a&amp;gt;&quot;
    },
...
</pre>
<p>So, if we define a function in our page with the same name as the invocation supplied by YQL, that function will be called and passed the JSON &#8216;payload&#8217;:</p>
<pre class="brush: jscript; title: ; notranslate">
// Somewhere in our page, above the YQL script element.
// This function must be called 'cbfunc' as that is the
// function that the YQL-returned JavaScript is calling
function cbfunc(yqlData) {

    // Do something cool with yqlData
    // ...

}
</pre>
<p>We now have a page that can consume data from Twitter.  And we are doing it all client-side! As you can probably tell, access to great data with no server-side setup makes me a happy developer.</p>
<h2>Using Dojo to Execute Dynamic YQL Queries</h2>
<p>Using YQL as demonstrated above is cool but also has the limitation that your query to YQL is completely static. Sure, the #dojo hashtag is interesting, but perhaps we want to build a user interface that allows a user to choose a different hashtag to search. Since JSON-P requires that we include our query via the <code>src</code> attribute in a script element in the page, providing the ability to do dynamic queries requires us to dynamically inject script elements. This sounds tricky, but don&#8217;t be scared, we have Dojo. Dojo provides an API called <a href="http://dojotoolkit.org/reference-guide/dojo/io/script.html">dojo.io.script</a> that makes dynamic script element injection easy. But an even slicker way of invoking YQL via Dojo is by using <a href="https://github.com/phiggins42/dojo-yql" target="_blank">this module that I found on GitHub</a>.  It abstracts away the usage of <code>dojo.io.script</code>, and let&#8217;s us interact with YQL at the &#8216;query&#8217; level. Using this module, we can write code like this:</p>
<pre class="brush: jscript; title: ; notranslate">
function doTwitterSearch(searchTerm) {
  var query =
    &quot;select * from twitter.search where q='&quot; + searchTerm + &quot;'&quot;;
  dojox.yql(query, {
    load: function(yqlData){
      // yqlData is the YQL JSON payload, do something neat with it
    ...
    }
 });
}
</pre>
<p>If that doesn&#8217;t strike you as cool, I&#8217;m sorry, but I don&#8217;t think that we can be friends. To use this module, download a <a href="http://dojotoolkit.org/download/">Dojo Source Build</a> and then plop the files from the GitHub repo into the dojox folder.<br />
<a href="http://www.enterprisedojo.com/wp-content/uploads/2011/06/dojox-yql-setup1.png"><img src="http://www.enterprisedojo.com/wp-content/uploads/2011/06/dojox-yql-setup1.png" alt="" title="dojox-yql-setup" width="196" height="156" class="alignnone size-full wp-image-1466" /></a></p>
<p>With those files in place, we can construct a page like this. This page loads Dojo, requires our <code>dojox.yql</code> module and demonstrates a simple YQL query to fetch the weather in Raleigh:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
  &lt;meta charset=&quot;utf-8&quot;&gt;
  &lt;title&gt;YQL and Dojo&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;&lt;/body&gt;
&lt;!-- Include dojo.js --&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;dojo/dojo/dojo.js&quot;&gt;&lt;/script&gt;

&lt;!-- dojo.require the YQL module from GitHub --&gt;
&lt;script&gt;
    dojo.require(&quot;dojox.yql&quot;);
&lt;/script&gt;

&lt;!-- Execute a query --&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
dojo.ready(function(){
  var query =
    &quot;select * from google.igoogle.weather where weather='Raleigh'&quot;;
	dojox.yql(query, {
		load: function(weatherData){
		  console.log(weatherData);
	    }
	});
});
&lt;/script&gt;
&lt;/html&gt;
</pre>
<h2>OK this is fun. But, I have a job.</h2>
<p>You may be wondering if YQL has any real usage outside of <a target="_blank" href="http://www.meetup.com/Triangle-JavaScript/events/23857831/">Hack Nights</a>. It does. The area of day-to-day software development that YQL really shines is the all-important product demo.  Almost all demo&#8217;s involve the use of &#8216;dummy&#8217; data.  Demo&#8217;s are often done at the prototype or proof-of-concept stage of a project and at this point, there likely isn&#8217;t any real data to be had.  When you find yourself needing some dummy data, you have two basic strategies to choose from: </p>
<ul>
<li><strong>The Boring Strategy</strong> Dummy up some simple data and in-line it into your app. Don&#8217;t think too hard about this. Just create an array of Employees or something.</li>
<li><strong>The Fun Strategy</strong> Put some thought into what data might be interesting for your demo. Use YQL to fetch this data. This will only take slightly more time than The Boring Strategy.</li>
</ul>
<p>The Fun Strategy is always better. I&#8217;ll show you what I mean. Click the button below to add a few dummy &#8216;Employee&#8217; records to the table.</p>
<div id="employeeContainer">
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Job</th>
</tr>
</thead>
<tbody id="employees">
  </tbody>
</table>
</div>
<p><button id="addEmployeeButton">Add Employee</button></p>
<p>Yawn. OK, now click this button a few times. It queries <a href="http://flickr.com" target="_blank">Flickr</a> for photographs of animals classified in the Order Rodentia, sorted by &#8216;Interesting-ness&#8217;.</p>
<div id="hamsterContainer"></div>
<p><button id="addHamsterButton">Add Interesting Rodent</button></p>
<p>How many employees did you add? And how many rodents? I bet you&#8217;ve got about 3 employees, and about 3 dozen of God&#8217;s more fluffy creatures. The point that I&#8217;m trying to make here is that all data are <strong>not</strong> created equal. Your demo will be much more compelling if you give your audience something that makes them smile.  Remember, people <strong>expect</strong> that your talk is going to be boring; it is a software demo after all. If you can beat the odds and grab people&#8217;s attention in the early going, they will stay engaged throughout the entirety of the demo, and you stand a much better chance of driving home whatever point it is that you are trying to make.</p>
<p>There&#8217;s a reason that most people use simple, hard-coded data in their demo&#8217;s. There was a time when using interesting data was simply not worth the effort. It usually involved <a target="_blank" href="http://www.urbandictionary.com/define.php?term=janky">janky</a> server-side code that did something nefarious like scrape the HTML of a Yahoo! or Google property.  YQL eliminates that hurdle and makes it dead-simple to pull fun data into your apps. </p>
<h2>An Example of a YQL-Driven App</h2>
<p>A few months ago, I used this exact technique for a personal project involving stock quote data. I&#8217;ve always loved quirky data visualizations, and for as long as I can remember I&#8217;ve had this idea for a visualization of stock quotes using fish. (Yes, I am crazy). I call it QuoteBowl. The basics of QuoteBowl involve a portfolio of stocks with each stock symbol in the portfolio represented by a goldfish in a fish bowl. If the stock is up on the day, the fish is rendered in a green color. If the stock is down, the fish is red. From there, the possibilities for fun visualizations are limitless. You could have different types of fish for different classes of stocks. You could draw the fish bigger or smaller depending on how much the stock was up or down. You could make the fish turn over and float upside down if the stock fell more than ten percent, etc, etc. I took a couple weekends and got a decent start. Check it out for yourself at <a target="_blank" href="http://quotebowl.com">quotebowl.com</a>. Add some fish. It&#8217;s fun!</p>
<p><center><br />
<a href="http://quotebowl.com" target="_blank"><img src="http://www.enterprisedojo.com/wp-content/uploads/2011/06/fishies.png" alt="" title="fishies" width="494" height="375" class="alignnone size-full wp-image-1469" /></a><br />
</center></p>
<p>Here is the code that drives the data. I am using the Yahoo! Finance YQL service to fetch quotes on the symbols that a user has added to the fish bowl. The symbols are stored as an array of strings called <code>userSymbols</code>:</p>
<pre class="brush: jscript; title: ; notranslate">
var query =
  'select symbol, LastTradePriceOnly, ChangeRealtime, ChangeinPercent from yahoo.finance.quotes where symbol in (' + userSymbols.join() + ')',

dojox.yql(query, {
  load: function( quoteData ) {
    // Add/Update the fish
  }
</pre>
<h2>Conclusion</h2>
<p>Software Demo&#8217;s are serious business. Everyday millions of dollars change hands, or don&#8217;t change hands, depending on how well a particular software demonstration went. That is not to say that every demo is mission critical, but regardless, the ability to give a great demo is a skill that every engineer should aspire to have. Given the right situation YQL may be the perfect tool for giving your demo the extra splash of flavor that it needs. Happy Demo&#8217;ing, and may all your fish be green.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.enterprisedojo.com/2011/07/21/building-neat-stuff-with-dojo-and-yql/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Dojo Beginner Gotcha: Accidental Static Fields</title>
		<link>http://www.enterprisedojo.com/2011/05/17/dojo-beginner-gotcha-accidental-static-fields/</link>
		<comments>http://www.enterprisedojo.com/2011/05/17/dojo-beginner-gotcha-accidental-static-fields/#comments</comments>
		<pubDate>Wed, 18 May 2011 01:14:22 +0000</pubDate>
		<dc:creator>Miko Borys</dc:creator>
				<category><![CDATA[Dojo]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[beginners]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[dojo]]></category>
		<category><![CDATA[gotcha]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[properties]]></category>
		<category><![CDATA[property]]></category>
		<category><![CDATA[static]]></category>
		<category><![CDATA[widget]]></category>

		<guid isPermaLink="false">http://www.enterprisedojo.com/?p=1371</guid>
		<description><![CDATA[Many developers with a background in Software Engineering are drawn to Dojo because of its ability to simulate classical type declaration and inheritance structures via <code>dojo.declare</code>.  Specifying a 'class' via <code>dojo.declare</code> is straight-forward, but an extremely common mistake involves the accidental declaration of a 'static field' (i.e. a class variable) when intending to declare an instance variable.]]></description>
			<content:encoded><![CDATA[<p>Many developers with a background in Software Engineering are drawn to Dojo because of its ability to simulate classical type declaration and inheritance structures via <code>dojo.declare</code>.  Specifying a &#8216;class&#8217; via <code>dojo.declare</code> is straight-forward, but an extremely common mistake involves the accidental declaration of a &#8216;static field&#8217; (i.e. a class variable) when intending to declare an instance variable.  Let&#8217;s jump right into an example to demonstrate.</p>
<h2>Mustang Sally</h2>
<p>Let&#8217;s use <code>dojo.declare</code> to specify a &#8216;class&#8217; for an Automobile. This Automobile will have five <strong>instance</strong> variables and zero <strong>class (static)</strong> variables.  The Automobile will have two String variables for its make and model, a Number variable for its year, an Array variable for a list of options, and an Object variable to describe its engine. One might think that a sensible way to declare this type would be something like:</p>
<pre class="brush: jscript; title: ; notranslate">
dojo.provide(&quot;machines.Automobile&quot;);

dojo.declare(&quot;machines.Automobile&quot;,  null, {
	/* summary:
	 * 		VROOOOM!
	 */

	make: &quot;&quot;,
	model: &quot;&quot;,
	year: null,				// YYYY
	options: [],
	engine: {
		horsepower: 0,
		size: 0
	}

	//...

});
</pre>
<p>Some of these instance variables are declared properly, but a few aren&#8217;t. Can you guess which ones are a problem? We&#8217;ll need to create an instance of our class to try it out. But first lets add a print() function to our “Automobile” class for convenience sake:</p>
<pre class="brush: jscript; title: ; notranslate">
	print: function() {

		// Dump the properties into the console
		console.log(&quot;%s %s %s. %s. %s hp, %f L.&quot;
				,this.year
				,this.make
				,this.model
				,this.options.toString()
				,this.engine.horsepower
				,this.engine.size
		);
	}
</pre>
<p>Let&#8217;s write some code to bash this &#8216;class&#8217; around a bit. Let&#8217;s create an Acura Integra with 160 horsepower and a 1.7 Liter engine. We&#8217;ll then call <code>print</code> on the Integra. Next, we&#8217;ll do the same for the 127 horsepower Honda Civic. Lastly, we&#8217;ll call <code>print</code> again on the Integra.</p>
<pre class="brush: jscript; title: ; notranslate">
	// Make a car
	var teg = new machines.Automobile();

	// Bring in the competition
	var civette = new machines.Automobile();

	// Set some properties on the first car
	teg.year = 1992;
	teg.make = &quot;Acura&quot;;
	teg.model = &quot;Integra&quot;;
	teg.options.push(&quot;Sunroof&quot;);
	teg.engine.horsepower = 160;
	teg.engine.size = 1.7;

	teg.print();

	// Set some properties on the second car
	civette.year = 1998;
	civette.make = &quot;Honda&quot;;
	civette.model = &quot;Civic&quot;;
	civette.options.push(&quot;Power Steering&quot;);
	civette.engine.horsepower = 127;
	civette.engine.size = 1.6;

	civette.print();

	// How's the teg doing?
    console.log(&quot;\tAfter setting the properties on the Civic, let's check back in on the Acura...&quot;);
	teg.print();
</pre>
<p>The output in Firebug&#8217;s console looks like this:<br />
<a href="http://www.enterprisedojo.com/wp-content/uploads/2011/05/firebugOne2.png"><img src="http://www.enterprisedojo.com/wp-content/uploads/2011/05/firebugOne2.png" alt="Firebug Console" title="firebugOne" width="574" height="78" class="alignnone size-full wp-image-1398" /></a></p>
<p>Hold your horses! Who swapped the Integra&#8217;s motor for the Civics&#8217;?! Problem? Indeed! Properties of the first car were overwritten by the second. Notice that the only properties that were overwritten were those that were instantiated as an array or object. So, if you guessed earlier that <code>options</code> and <code>engine</code> were the troublesome fields, you shouldn&#8217;t be reading this tutorial as you are a Dojo genius! The moral of the story is to be wary of instantiating properties as types other than the simple string, number, or boolean. Any fields declared in-line as complex objects will be treated as &#8216;static&#8217; properties shared between all instances of that type.</p>
<h2>This is How We Do It</h2>
<p>If you would like to use a complex object as a field, hope is not lost. The proper way to do this is to set the variable to <code>null</code> initially, and then instantiate it in your type&#8217;s constructor function like so:</p>
<pre class="brush: jscript; title: ; notranslate">
//...
	make: &quot;&quot;,
	model: &quot;&quot;,
	year: null,				// YYYY
	options: null,
	engine: null,

	constructor: function() {
		this.options = [];
		this.engine = {
				horsepower: 0,
				size: 0
		};
	},
//...
</pre>
<p>But hey, don&#8217;t hate on statics just yet! The concept of static class properties can be very useful. In our example, let&#8217;s assume that every Automobile had a standard set of options that was identical for each (A/C, cruise control, sunroof, etc) and we wanted to create an enumeration of these options. This would be an ideal candidate for a static array. The key to effective use of <code>dojo.declare</code> is to avoid <strong>accidentally</strong> creating a static variable when an instance variable is intended.  Another important skill is to recognize when you have made this mistake. It is very easy to make and even veteran Dojo-slingers do it. If during a debugging session, you ever encounter a scenario where the properties of one instance of a <code>dojo.declare</code>&#8216;d type is trampling another&#8217;s, you should immediately think <strong>ACCIDENTAL STATIC ALERT!</strong><center><img alt="Static Electricity" src="http://4.bp.blogspot.com/__mMx7lCefGY/Sbj6RK7J6bI/AAAAAAAAAI8/bBmwddtgIXA/s400/Static-Electricity-II-TW.png" title="Static FIelds" class="alignleft" width="400" height="267" /></center></p>
]]></content:encoded>
			<wfw:commentRss>http://www.enterprisedojo.com/2011/05/17/dojo-beginner-gotcha-accidental-static-fields/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>On Dojo Array Functions and Good Beer</title>
		<link>http://www.enterprisedojo.com/2011/02/24/on-dojo-array-functions-and-good-beer/</link>
		<comments>http://www.enterprisedojo.com/2011/02/24/on-dojo-array-functions-and-good-beer/#comments</comments>
		<pubDate>Fri, 25 Feb 2011 04:19:24 +0000</pubDate>
		<dc:creator>Dan Lee</dc:creator>
				<category><![CDATA[Dojo]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[beer?]]></category>
		<category><![CDATA[dojo]]></category>
		<category><![CDATA[dojo.filter]]></category>
		<category><![CDATA[dojo.forEach]]></category>
		<category><![CDATA[dojo.map]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.enterprisedojo.com/?p=1128</guid>
		<description><![CDATA[The other day, I was working on a Dojo-based project and was paring down a JavaScript array using the ultra-slick <code>dojo.filter</code> function. As I was effortlessly discarding the unwanted array elements, I had the thought, "Man, I really could have used <code>dojo.filter</code> when I was trying to get rid of those Busch beers!". The revelation at the handiness of <code>dojo.filter</code> made me realize that the Dojo array functions deserve a blog post of their own. And what better contrived data set than an array of beers? ]]></description>
			<content:encoded><![CDATA[<p><script src="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js" type="text/javascript"></script><br />
<script type="text/javascript" src="/postresources/beers/beercodeforblog.js"></script></p>
<link rel="stylesheet" href="/postresources/beers/beers.css" type="text/css">
<p>My dad is not a JavaScript programmer, but he does have something in common with nearly all of us; a deep and passionate love of beer.  Unlike most JavaScripters, however, my dad&#8217;s favorite brew is on the lower-end of the quality spectrum. When he reaches for a cold one, he <strong>Heads for the Mountains</strong>. Yes, my dad&#8217;s favorite beer is <a href="http://www.busch.com/" target="_blank">Busch</a>. This presents a problem when he makes the journey from Maine to North Carolina for a visit. Being the good son that I am, I make sure my fridge is stocked with a case upon his arrival. Inevitably though, he never finishes all of them before heading home. I can&#8217;t be certain, but I&#8217;m quite sure the first person to ever utter the phrase <em>&#8216;You can&#8217;t give these things away!&#8217;</em> was faced with a Busch beer surplus . After his most recent visit, I turned to Facebook to help myself out&#8230;</p>
<div><a href="http://www.enterprisedojo.com/wp-content/uploads/2011/01/fbpost.png"><img src="http://www.enterprisedojo.com/wp-content/uploads/2011/01/fbpost.png" alt="" title="fbpost" width="485" height="372" class="alignnone size-full wp-image-1137" /></a></div>
<p>I don&#8217;t want to brag or anything, but I have well over 100 Friends on Facebook. Would you believe not one of them took these fine beverages off my hands? There are some problems even Mark Zuckerberg can&#8217;t solve.</p>
<h2>If Life Were Software</h2>
<p>The other day, I was working on a Dojo-based project and was paring down a JavaScript array using the ultra-slick <code>dojo.filter</code> function. As I was effortlessly discarding the unwanted array elements, I had the thought, &#8220;Man, I really could have used <code>dojo.filter</code> when I was trying to get rid of those Busch beers!&#8221;. (Am I the only one that wishes for the ability to apply software-based solutions to our physical world? Surely I&#8217;m not the only person that gets an overwhelming urge to do a <code>ctrl-f</code> while hopelessly searching the aisles at Wal-Mart?).  The revelation at the handiness of <code>dojo.filter</code> made me realize that the Dojo array functions deserve a blog post of their own. And what better contrived data set than an array of beers? </p>
<h2>Some Silly Data</h2>
<p>In this article, we will use the following array. It contains two Busch beers and an assortment of <strong>good</strong> beers.  Each beer object contains two strings, one representing the brand of beer, and a second that contains a path to an image of that beer&#8217;s logo.</p>
<pre class="brush: jscript; title: ; notranslate">
	var beersData = [
	  {&quot;brand&quot;:&quot;Busch&quot;, &quot;image&quot;:&quot;images/busch.png&quot;},
	  {&quot;brand&quot;:&quot;Blue Moon&quot;, &quot;image&quot;:&quot;images/bluemoon.png&quot;},
	  {&quot;brand&quot;:&quot;Fat Tire&quot;, &quot;image&quot;:&quot;images/fattire.png&quot;},
	  {&quot;brand&quot;:&quot;Stella Artois&quot;, &quot;image&quot;:&quot;images/stellaartois.png&quot;},
	  {&quot;brand&quot;:&quot;Busch&quot;, &quot;image&quot;:&quot;images/busch.png&quot;}
	];
</pre>
<p><em>Note: I am of the extremely rare classification of JavaScript programmer that does not drink. Therefore, I have no idea if these beers are any good. I queried the most sophisticated of my IBM colleagues for their favorite beer and these names kept coming up, so I trust that they must represent the very best beers in the world.</em></p>
<h2>dojo.forEach</h2>
<p>We&#8217;ll begin our investigation of the Dojo array functions with a look at the workhorse <code>dojo.forEach</code>. It&#8217;s true that <code>dojo.forEach</code> is just a syntactically sugared version of a for-loop, but oh how sweet it is.  In its simplest form, <code>dojo.forEach</code> is passed an array and a function that gets executed on each member of that array. The following code uses <code>dojo.forEach</code> to craft a function called <code>beersToDOM</code> which creates an <code>img</code> element for each beer in our array.</p>
<pre class="brush: jscript; title: ; notranslate">
dojo.ready(function(){
	var beersData = [
	  {&quot;brand&quot;:&quot;Busch&quot;, &quot;image&quot;:&quot;images/busch.png&quot;},
	  {&quot;brand&quot;:&quot;Blue Moon&quot;, &quot;image&quot;:&quot;images/bluemoon.png&quot;},
	  {&quot;brand&quot;:&quot;Fat Tire&quot;, &quot;image&quot;:&quot;images/fattire.png&quot;},
	  {&quot;brand&quot;:&quot;Stella Artois&quot;, &quot;image&quot;:&quot;images/stellaartois.png&quot;},
	  {&quot;brand&quot;:&quot;Busch&quot;, &quot;image&quot;:&quot;images/busch.png&quot;}
	];

	var beersToDOM = function(beers, target) {
		dojo.forEach(beers, function(beer){
			dojo.create(&quot;img&quot;, {&quot;src&quot;:beer.image}, target);
		});
	};
	beersToDOM(beersData, dojo.byId('foreachDemo'));
});
</pre>
<p><button id="runForEachDemo">Run this code</button></p>
<p>This <code>div</code> has an id of <code>foreachDemo</code>.</p>
<div id="foreachDemo" class="beerContainer forEach"></div>
<p>It also bears noting that the arguments passed to <code>dojo.forEach</code>&#8216;s callback function include two other parameters that I omitted from the above example. In addition to the current array element, the array index (&#8220;i value&#8221;), and a reference to the array itself are also passed.  It is often-times helpful to have these bits of information while iterating over arrays.  Here is the same <code>forEach</code> code with those arguments specified:</p>
<pre class="brush: jscript; title: ; notranslate">
dojo.forEach(beers, function(beer, index, array){
	dojo.create(&quot;img&quot;, {&quot;src&quot;:beer.image}, target);
});
</pre>
<p>Another nifty feature of <code>dojo.forEach</code> is the optional scope parameter. Passing an object as the final argument to <code>forEach</code> results in the callback function being executed in the scope of that object. This means that the &#8216;this&#8217; in the callback function will be the object you pass it.</p>
<pre class="brush: jscript; title: ; notranslate">
dojo.forEach(array,
 function(item, index, originalArray) {...},
 obj); // Invokes the function in the scope of 'obj'
</pre>
<h2>dojo.filter</h2>
<p><code>dojo.filter</code> looks much like <code>dojo.forEach</code>. Its arguments are an array and a function to run on each array member. <code>dojo.filter</code> returns a new array whose contents are determined by the boolean return value of its callback function. If <code>true</code> is returned for an individual array item, that item is included in the new array. If <code>false</code> is returned, that item is excluded. Look at how elegantly we can return a new array that contains none of the undesirable Busch beers.    </p>
<pre class="brush: jscript; title: ; notranslate">
	var skunkFree =
		dojo.filter(beersData,
			function(beer){ return beer.brand != &quot;Busch&quot;; }
		);
	beersToDOM(skunkFree, dojo.byId('filterDemo'));
</pre>
<p><button id="runFilterDemo">Run this code</button></p>
<p>This <code>div</code> has an id of <code>filterDemo</code>.</p>
<div id="filterDemo" class="beerContainer filter"></div>
<div style="margin-top:1em">
<h2>dojo.map</h2>
</div>
<p>Getting rid of the Busch beers was a solid accomplishment, but it would be much better if we could somehow transform them into good beers. For this Rumpelstiltskin-esque task, we&#8217;ll turn to <code>dojo.map</code>. <code>dojo.map</code> runs its callback function on every item in the array and creates a new array containing the return values of each invocation of the function. Let&#8217;s write a function that detects if an array item is a Busch beer. If so, we&#8217;ll return an object literal representing a Blue Moon.  If the beer is not a Busch, we&#8217;ll return a copy of that perfectly-fine-as-it-is beer.</p>
<pre class="brush: jscript; title: ; notranslate">
var beerAlchemy = dojo.map(beersData, function(beer) {
 return beer.brand === &quot;Busch&quot; ?
  {
	 &quot;brand&quot;:&quot;Blue Moon&quot;,
     &quot;image&quot;:&quot;images/bluemoon.png&quot;
  } : dojo.clone(beer);
});
beersToDOM(beerAlchemy, dojo.byId('mapDemo'));
</pre>
<p><button id="runMapDemo">Run this code</button></p>
<p>This <code>div</code> has an id of <code>mapDemo</code>.</p>
<div id="mapDemo" class="beerContainer map"></div>
<div style="margin-top:1em">
<h2>dojo.some and dojo.every</h2>
</div>
<p>Rounding out the Dojo Array functions are two simple functions that return boolean values. <code>dojo.some</code> returns <code>true</code> if some of the items in the passed array return <code>true</code> for the passed callback function. <code>dojo.every</code> returns <code>true</code> if <em>all</em> of the items in the passed array return <code>true</code> for the callback function. As a simple example, here is a function that does a sniff test to determine if the beer is a Busch.  <code>dojo.some</code> returns <code>true</code> because there are two Busch beers in the array. <code>dojo.every</code> returns <code>false</code> because the array is not entirely composed of Busch beers.</p>
<pre class="brush: jscript; title: ; notranslate">
var beersData = [
	  {&quot;brand&quot;:&quot;Busch&quot;, &quot;image&quot;:&quot;images/busch.png&quot;},
	  {&quot;brand&quot;:&quot;Blue Moon&quot;, &quot;image&quot;:&quot;images/bluemoon.png&quot;},
	  {&quot;brand&quot;:&quot;Fat Tire&quot;, &quot;image&quot;:&quot;images/fattire.png&quot;},
	  {&quot;brand&quot;:&quot;Stella Artois&quot;, &quot;image&quot;:&quot;images/stellaartois.png&quot;},
	  {&quot;brand&quot;:&quot;Busch&quot;, &quot;image&quot;:&quot;images/busch.png&quot;}
	];

var skunkTest = function(beer) {
	return beer.brand === &quot;Busch&quot;;
}
var hasSkunk = dojo.some(beersData, skunkTest);  // TRUE
var nuthinButSkunk = dojo.every(beersData, skunkTest);  // FALSE
</pre>
<h2>Array functions, the key to cleaner code</h2>
<p>Before discovering the array functions, many Dojo newcomers transitioning from Java or C#  find themselves lost without formal &#8216;Collection&#8217; types.  It&#8217;s not long before things like  <code>function contains(array, object){...}</code> are springing up all over the place. Writing helper-functions like this is a natural reaction, but almost always unnecessary. When used proficiently just about all array manipulation tasks can be completed using <code>forEach</code>, <code>filter</code>, <code>map</code>, <code>some</code>, or <code>every</code>. Mastering these functions will result in concise and readable array manipulation code, definitely something worth raising a glass to.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.enterprisedojo.com/2011/02/24/on-dojo-array-functions-and-good-beer/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>A Simple Dojo DataGrid Example (or so close, yet wide right&#8230;)</title>
		<link>http://www.enterprisedojo.com/2011/01/31/a-simple-dojo-datagrid-example-or-so-close-yet-wide-right/</link>
		<comments>http://www.enterprisedojo.com/2011/01/31/a-simple-dojo-datagrid-example-or-so-close-yet-wide-right/#comments</comments>
		<pubDate>Tue, 01 Feb 2011 04:27:27 +0000</pubDate>
		<dc:creator>Chris Jaun</dc:creator>
				<category><![CDATA[Dojo]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[DataGrid]]></category>
		<category><![CDATA[dojo]]></category>
		<category><![CDATA[example]]></category>

		<guid isPermaLink="false">http://www.enterprisedojo.com/?p=1022</guid>
		<description><![CDATA[The Dojo DataGrid is the Super Bowl of widgets. Newcomers flock to it! Everyone wants one on their page, but it is not easy to win the Super Bowl, nor is it easy to conquer the Grid. ]]></description>
			<content:encoded><![CDATA[<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojox/grid/resources/Grid.css" />
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojox/grid/resources/claroGrid.css" />
<p><script src="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js.uncompressed.js" type="text/javascript" djConfig="parseOnLoad:true"></script></p>
<p><script src="/postresources/simpledatagrid/simpleDataGrid.js" type="text/javascript" ></script></p>
<p>The Dojo DataGrid is the Super Bowl of widgets. Newcomers flock to it! Everyone wants one on their page, but it is not easy to win the Super Bowl, nor is it easy to conquer the Grid. The first time I got one working I took a victory lap around the office, high-fiving co-workers who stared back at me suspiciously. It was pretty awesome. Unfortunately, many people never experience that moment of ecstasy, or if they do, it is after many long hours of pain. You may feel like your code matches an example from the web exactly, but no matter what you do, the Grid will just not show up! Trust me, I know how it feels to be so close to your goal, yet continually come up short (or wide right, as it may be), I am a fan of the Buffalo Bills.</p>
<p><center><a href="http://www.enterprisedojo.com/wp-content/uploads/2011/01/bills-e1296088955731.jpg"><img src="http://www.enterprisedojo.com/wp-content/uploads/2011/01/bills-300x225.jpg" alt="Chris in Bills shirt" title="Bills shirt" width="300" height="225" class="size-medium wp-image-1074" /></a></center></p>
<p>This post will feature a simple, all inclusive, example for populating a Grid with data and displaying it on your web page. We will start with the basic page set up, including the style sheets, then move on to writing the necessary markup and JavaScript code. The DataGrid really isn&#8217;t that hard, you just need to understand all its parts.</p>
<h2>Buffalo Bill Greats and their Super Bowl Victories</h2>
<p>In honor of the 20th Anniversary (January 27, 1991) of one of the most traumatic memories from my childhood (see this <a href="http://www.youtube.com/watch?v=BCHZFwDCNyA" target="_blank">YouTube video</a> if you don&#8217;t know what I&#8217;m talking about), I reluctantly present you the following Grid:</p>
<div class="claro" style="width: 500px; height: 130px">
<table id="billsGrid" dojoType="dojox.grid.DataGrid">
<thead>
<tr>
<th field="number">Number</th>
<th field="name">Name</th>
<th field="position">Position</th>
<th field="victories" width="150px">Super Bowl Victories</th>
</tr>
</thead>
</table></div>
<p>Notice some of the nice built-in features of the Dojo DataGrid, such as column sorting and row highlighting. Below you will find all the code required to produce this Grid. Keep heading down the page and we&#8217;ll go over the pieces in detail.</p>
<h2>A Single Page Dojo DataGrid Example</h2>
<pre class="brush: xml; title: ; notranslate">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;The Simplest Dojo DataGrid Example of All Time&lt;/title&gt;
&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot;
 href=&quot;http://ajax.googleapis.com/ajax/libs/dojo/1.5/dijit/themes/claro/claro.css&quot; /&gt;

&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot;
 href=&quot;http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojox/grid/resources/Grid.css&quot; /&gt;

 &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot;
 href=&quot;http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojox/grid/resources/claroGrid.css&quot; /&gt;
&lt;/head&gt;

&lt;body class=&quot;claro&quot;&gt;
	&lt;div style=&quot;width: 600px; height: 200px&quot;&gt;
		&lt;table id=&quot;billsGrid&quot; dojoType=&quot;dojox.grid.DataGrid&quot;&gt;
	  		&lt;thead&gt;
	    		&lt;tr&gt;
	      			&lt;th field=&quot;number&quot;&gt;Number&lt;/th&gt;
	      			&lt;th field=&quot;name&quot;&gt;Name&lt;/th&gt;
	      			&lt;th field=&quot;position&quot;&gt;Position&lt;/th&gt;
	      			&lt;th field=&quot;victories&quot; width=&quot;180px&quot;&gt;Super Bowl Victories&lt;/th&gt;
	    		&lt;/tr&gt;
	  		&lt;/thead&gt;
		&lt;/table&gt;
	&lt;/div&gt;

&lt;script type=&quot;text/javascript&quot;
 src=&quot;http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js&quot;
	djConfig=&quot;parseOnLoad:true&quot;&gt;&lt;/script&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
	dojo.require(&quot;dojox.grid.DataGrid&quot;);
	dojo.require(&quot;dojo.data.ItemFileReadStore&quot;);
&lt;/script&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
dojo.ready(function() {
	var theGreatestTeamOfAllTime = {
		items: [ {
				  &quot;number&quot;:&quot;12&quot;,
				  &quot;name&quot;:&quot;Jim Kelly&quot;,
				  &quot;position&quot;:&quot;QB&quot;,
				  &quot;victories&quot;:&quot;0&quot;
				  },
		         {
				  &quot;number&quot;:&quot;34&quot;,
				  &quot;name&quot;:&quot;Thurman Thomas&quot;,
				  &quot;position&quot;:&quot;RB&quot;,
				  &quot;victories&quot;:&quot;0&quot;
				  },
		         {
				  &quot;number&quot;:&quot;89&quot;,
				  &quot;name&quot;:&quot;Steve Tasker&quot;,
				  &quot;position&quot;:&quot;WR&quot;,
				  &quot;victories&quot;:&quot;0&quot;
				  },
			{
				&quot;number&quot;:&quot;78&quot;,
				&quot;name&quot;:&quot;Bruce Smith&quot;,
				&quot;position&quot;:&quot;DE&quot;,
				&quot;victories&quot;:&quot;0&quot;
			}
		       ],
		identifier: &quot;number&quot;
	};

	var dataStore =
	new dojo.data.ItemFileReadStore(
		{ data:theGreatestTeamOfAllTime }
	);
	var grid = dijit.byId(&quot;billsGrid&quot;);
	grid.setStore(dataStore);
});
&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<h2>Step 1: Include Dojo on your page</h2>
<p>Starting on line #29, Dojo is included on the page. In this example we are pointing to the copy of Dojo hosted on the Google CDN. The important thing to take away from this line is the <code>djConfig="parseOnLoad:true"</code> attribute. When <code>parseOnLoad</code> is set to true the <a href="http://dojotoolkit.org/reference-guide/dojo/parser.html">Dojo parser</a> will automatically search for tags containing a <code>dojoType</code> attribute and replace that element with the markup of the specified widget. If you are unfamiliar with Dojo Widgets, I recommend reading <a href="http://www.enterprisedojo.com/2010/09/21/introduction-to-custom-dojo-widgets/" target="_blank">Dan&#8217;s article on the subject</a>. If you forget to add the <code>parseOnLoad:true</code> parameter, you&#8217;re going to end up with a very boring HTML table instead of a fancy Dojo DataGrid. This is a very common mistake.</p>
<h2>Step 2: Add the style sheets</h2>
<p>Being that the DataGrid is the Super Bowl of widgets it gets some special treatment when it comes to styling. Unlike most widgets, the Grid has its own set of style sheets. In the <strong>HEAD</strong> section of the example you&#8217;ll see the standard <em>Claro</em> theme style sheet is included, but directly below it the <em>grid.css</em> and <em>gridClaro.css</em> files are also added. This is very important. If you don&#8217;t include those, your Grid won&#8217;t even be recognizable! See&#8230;</p>
<p><a href="http://www.enterprisedojo.com/wp-content/uploads/2011/01/noStyleGrid.jpg"><img src="http://www.enterprisedojo.com/wp-content/uploads/2011/01/noStyleGrid.jpg" alt="Grid without grid style sheets" title="No Style Grid" width="273" height="139" class="alignnone size-full wp-image-1100" /></a></p>
<p>On line #15, in the body tag, the Claro class is specified. This, combined with the style sheet includes, will load all of the necessary styling information for your Grid.</p>
<h2>Step 3: Require the necessary modules</h2>
<p>Dojo 101 lesson reminder&#8230;if you are using a specific Dojo type on your page you need to require it. Starting on line #34 we include the <code>dojox.grid.DataGrid</code> and the <code>dojo.data.ItemFileReadStore</code>. We&#8217;ll see how these are used momentarily.</p>
<h2>Step 4: The Markup</h2>
<p>There are three main parts to the markup of our example DataGrid.</p>
<ul>
<li>
The surrounding <code>div</code> tag (line #16) wraps the table markup and contains settings for the height and width. The Dojo DataGrid tends not to show up if no sizing information is specified, so don&#8217;t forget this part.</li>
<li>The <code>table</code> tag (line #17) contains the <code>dojoType="dojox.grid.DataGrid"</code> attribute. This is the attribute the Dojo parser looks for when the page loads and thus this element represents the element that will be replaced with the Grid&#8217;s markup. Also notice that an <code>id</code> for the table is specified inside the <code>table</code> tag. This <code>id</code> will be referenced later in the JavaScript code used to populate the Grid.</li>
<li>You need to add a <code>th</code> tag for each column in your data set that you want displayed in the DataGrid. Each column header tag contains a <code>field</code> attribute. This attribute corresponds to the name of a field in a data store that contains your data. Table rows will automatically be generated for each entry in your data store. (More on data stores in a bit).</li>
</ul>
<h2>Step #5: The JavaScript code</h2>
<p>The JavaScript code to populate the Grid begins on line #39 with a call to <code>dojo.ready()</code>. <code>dojo.ready</code> is a synonym for <a href="http://dojotoolkit.org/reference-guide/dojo/addOnLoad.html#dojo-addonload">dojo.addOnLoad</a>.  This function ensures that the function passed in as an argument only executes after the DOM is ready, preventing us from operating on the DataGrid object before it has been created.</p>
<p>The coolest part about the Grid is that it utilizes the <a href="http://dojotoolkit.org/reference-guide/dojo/data.html" target="_blank">dojo.data API</a>. You can use any Data Store that conforms to the dojo.data API with the Grid. For our example, we will use Dojo&#8217;s built-in <a href="http://dojotoolkit.org/reference-guide/dojo/data/ItemFileReadStore.html" target="_blank">ItemFileReadStore</a>.</p>
<p>Inside the function our first step is to create an object literal in JSON format that contains the data we want to display in the Grid. (In an actual application this data would likely be pulled in from a database or other web service). The structure of this data is <em>very important</em>. The <code>ItemFileReadStore</code> requires a very specific format. First, it must have a field named <em>items</em> that contains an array of objects that represent the data. Second, it needs to contain a field named <em>identifier</em> that specifies the primary key of the data. Neglecting to put your data in this format is an extremely common mistake when dealing with the <code>ItemFileReadStore</code>.</p>
<p>On line #69 the <code>dojo.data.ItemFileReadStore</code> object is created. It requires a single argument, the object literal object in JSON format defined right above it and described in the previous paragraph.</p>
<p>Lastly, the Grid object itself is retrieved via a call to <code>dijit.byId("billsGrid")</code>, passing in the ID of the table as specified in the markup on line #17. The retrieved Grid object then has the ItemFileReadStore set on it. Setting the store will cause the Grid to load and display the data.  </p>
<h2>Putting it through the uprights</h2>
<p>The intent of this article was to get you started with the Grid. Maybe this example represented your very first experience with Dojo, and I hope that it steered you clear of some of the mistakes most Dojo newcomers make. If you are brand new to Dojo, you can copy and paste the code example into an HTML file and it will work. But if you want to have consistent success over the long term (like those damn Pittsburgh Steelers), take this example and study it.  Take the time to learn the different components and how everything works together. After you have the Grid running, experiment with some of the other widgets available in <a href="http://dojotoolkit.org/reference-guide/dijit/" target="_blank">the Dijit library</a>.</p>
<p>In future articles we will look into some more advanced Grid topics, such as inline editing, moving things around, paging, event handling, and all those other exciting things one can do with a Grid. Any special requests? Post them in the comments!</p>
<p>Grid Reference: <a href="http://dojotoolkit.org/reference-guide/dojox/grid/DataGrid.html">http://dojotoolkit.org/reference-guide/dojox/grid/DataGrid.html</a></p>
<p>Good luck and go Packers (next week) and go Bills (next year)!!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.enterprisedojo.com/2011/01/31/a-simple-dojo-datagrid-example-or-so-close-yet-wide-right/feed/</wfw:commentRss>
		<slash:comments>37</slash:comments>
		</item>
		<item>
		<title>Beware the Trailing Comma of Death</title>
		<link>http://www.enterprisedojo.com/2010/12/19/beware-the-trailing-comma-of-death/</link>
		<comments>http://www.enterprisedojo.com/2010/12/19/beware-the-trailing-comma-of-death/#comments</comments>
		<pubDate>Mon, 20 Dec 2010 04:28:18 +0000</pubDate>
		<dc:creator>Dan Lee</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[dojo]]></category>
		<category><![CDATA[Internet Explorer]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mistakes]]></category>

		<guid isPermaLink="false">http://www.enterprisedojo.com/?p=885</guid>
		<description><![CDATA[When you use a JavaScript library, does this mean that your days of browser-specific issues are over?  Should you just test your code in the latest version of Chrome and call it a day? Of course not. There still exists an entire class of programming errors that introduce bugs that only appear in certain browsers. Of these problems, none of them are more sinister than........the <strong>Trailing Comma of Death</strong>.]]></description>
			<content:encoded><![CDATA[<p>JavaScript libraries like <a href="http://jquery.com/" target="_blank">jQuery</a> and my beloved <a href="http://www.dojotoolkit.org" target="_blank">Dojo</a> are nothing short of miracle workers when it comes to enabling developers to write code that works consistently across multiple browsers.  These libraries provide simple APIs and perform an unfathomable amount of work &#8220;under the covers&#8221; to ensure that these APIs work consistently.  They save us countless hours of debugging browser-specific problems, and more importantly, keep us from inventing hacks to work around these bugs. Really and truly, the developers that maintain these libraries are heroes. The web would look nothing like it does without them.</p>
<h2>Not out of the woods</h2>
<p>Does the use of a JavaScript library mean your days of browser-specific issues are over?  Should you just test your code in the latest version of Chrome and call it a day? Of course not. There still exists an entire class of programming errors that only appear as bugs in certain browsers. Of these, none is more sinister than&#8230;&#8230;..the <strong>Trailing Comma of Death</strong>.</p>
<p><a href="http://www.enterprisedojo.com/wp-content/uploads/2010/12/tcd.png"><img class="aligncenter size-full wp-image-905" title="tcd" src="http://www.enterprisedojo.com/wp-content/uploads/2010/12/tcd.png" alt="" width="448" height="348" /></a></p>
<p>This is my affectionate nickname for the oh-so-common mistake of adding a comma after the final declared property within a JavaScript object. Here is a contrived example.  Note the extra comma after the declaration of the <code>get2</code> function.</p>
<pre class="brush: jscript; title: ; notranslate">
dojo.ready(function() {
	var testObject = function() {
		var testString1 = &quot;Trailing commas? &quot;;
		var testString2 = &quot;They don't scare me.&quot;;
		return {
			get1 : function() {
				return testString1;
			},
			get2 : function(){
				return testString2;
			},
          // ^ Trailing Comma of Death
		};
	};

	var t = testObject();
	dojo.byId(&quot;commaTest&quot;).innerHTML = t.get1() + t.get2();
});
</pre>
<p>Let&#8217;s look at a series of screenshots that shows the output of the above code in Firefox, Chrome, and Internet Explorer. Assume that Dojo is included in the page, and that there exists a <code>div</code> element with an id of &#8216;<code>commaTest</code>&#8216;.</p>
<p>Here&#8217;s what it looks like in Firefox 3.6:</p>
<p><a href="http://www.enterprisedojo.com/wp-content/uploads/2010/12/firefoxtest.png"><img class="aligncenter size-full wp-image-922" style="border: 1px solid lightgrey; padding: 6px;" title="firefoxtest" src="http://www.enterprisedojo.com/wp-content/uploads/2010/12/firefoxtest.png" alt="" width="400" height="300" /></a></p>
<p>In Google Chrome 9:</p>
<p><a href="http://www.enterprisedojo.com/wp-content/uploads/2010/12/chromeTest.png"><img class="aligncenter size-full wp-image-921" style="border: 1px solid lightgrey; padding: 6px;" title="chromeTest" src="http://www.enterprisedojo.com/wp-content/uploads/2010/12/chromeTest.png" alt="" width="399" height="300" /></a></p>
<p>And in Internet Explorer 8:</p>
<p><a href="http://www.enterprisedojo.com/wp-content/uploads/2010/12/ieTest.png"><img class="aligncenter size-full wp-image-923" style="border: 1px solid lightgrey; padding: 6px;" title="ieTest" src="http://www.enterprisedojo.com/wp-content/uploads/2010/12/ieTest.png" alt="" width="400" height="300" /></a></p>
<p>Wuh-oh, what happened in Internet Explorer? It turns out that the trailing comma is right on the edge as to what is permissible JavaScript syntax. Internet Explorer does not tolerate a trailing comma while the rest of the browsers do. The lesson? <strong>Internet Explorer is terrified of the Trailing Comma of Death</strong>.</p>
<p><a href="http://www.enterprisedojo.com/wp-content/uploads/2010/12/ie_is_scared1.png"><img class="aligncenter size-full wp-image-910" title="ie_is_scared" src="http://www.enterprisedojo.com/wp-content/uploads/2010/12/ie_is_scared1.png" alt="" width="531" height="644" /></a></p>
<p>That this issue is specific to Internet Explorer makes for a very dicey situation. Web developers tend to use the &#8220;any-browser-but-IE&#8221; strategy as they develop their JavaScript code because the debugging tools provided by those browsers are so much better. This means that most developers fire up Internet Explorer only as a last step in code verification, and will not catch trailing comma problems until that point. Thankfully the Developer Tools console of IE8 usually gives a nice, clear error when a trailing comma is encountered:</p>
<p><a href="http://www.enterprisedojo.com/wp-content/uploads/2010/12/ieDevtools.png"><img class="aligncenter size-full wp-image-924" title="ieDevtools" src="http://www.enterprisedojo.com/wp-content/uploads/2010/12/ieDevtools.png" alt="" width="434" height="395" /></a></p>
<h2>A Harrowing Tale</h2>
<p>You may be wondering why I think the trailing comma problem is a big deal. How on Earth could it make its way into a production code-base? Well, my skeptical friends, let me tell you a story&#8230;.. </p>
<p>There once was a newly minted JavaScript programmer who was given his very first assignment. We&#8217;ll call him Stan Dee. Stan was asked to write a simple Dojo widget, something his boss thought would be a good introductory work item. Naturally, Stan wanted his first code delivery to be flawless, elegant, and clever. You know, in case any of his new team-mates happened to see it in the commit logs. Stan wrote the widget and tested it obsessively in all of the product&#8217;s supported browsers, and even in one that isn&#8217;t officially supported. It looked great. As he was about to commit his work and move on, Stan noticed a block of code in his widget that was unnecessarily repeated. A firm believer in the <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a> principle, Stan could not do the commit before abstracting the duplicate code into its own function. He was using Dojo&#8217;s animation features to pull off a fade-out technique and had almost exactly the same code in two places.</p>
<p><a href="http://www.enterprisedojo.com/wp-content/uploads/2010/12/needsRefactor2.png"><img class="alignnone size-full wp-image-935" style="border: 1px solid lightgrey; padding: 6px;" title="needsRefactor" src="http://www.enterprisedojo.com/wp-content/uploads/2010/12/needsRefactor2.png" alt="" width="528" height="447" /></a></p>
<p>Stan sought to DRY this situation out a bit. He created a new function in the file. Stan, like all developers, is lazy. Instead of typing out the necessary code, he swiped an already existing function, copied it, and pasted it at the end of the widget&#8217;s function declarations, and changed the name:</p>
<p><a href="http://www.enterprisedojo.com/wp-content/uploads/2010/12/refactorStage1.png"><img class="alignnone size-full wp-image-937" style="border: 1px solid lightgrey; padding: 6px;" title="refactorStage1" src="http://www.enterprisedojo.com/wp-content/uploads/2010/12/refactorStage1.png" alt="" width="520" height="616" /></a></p>
<p>Stan then cleaned up the rest of the code, replacing the contents of the new function with the appropriate code and updating the other functions to invoke the new common one:</p>
<p><a href="http://www.enterprisedojo.com/wp-content/uploads/2010/12/refactorDone2.png"><img class="alignnone size-full wp-image-941" style="border: 1px solid lightgrey; padding: 6px;" title="refactorDone" src="http://www.enterprisedojo.com/wp-content/uploads/2010/12/refactorDone2.png" alt="" width="479" height="418" /></a></p>
<p>Along the way, Stan made one glaring mistake. Did you catch it? What&#8217;s that laughter? Oh, it appears as though somebody has spotted the problem:</p>
<div style="border: 1px solid lightgrey; padding: 6px;">
<p><a href="http://www.enterprisedojo.com/wp-content/uploads/2010/12/refactorDONECircle.png"><img class="alignnone size-full wp-image-942" title="refactorDONECircle" src="http://www.enterprisedojo.com/wp-content/uploads/2010/12/refactorDONECircle.png" alt="" width="481" height="417" /></a><br />
<a href="http://www.enterprisedojo.com/wp-content/uploads/2010/12/loltcd.png"><img class="alignnone size-full wp-image-943" title="loltcd" src="http://www.enterprisedojo.com/wp-content/uploads/2010/12/loltcd.png" alt="" width="450" height="481" /></a></p>
</div>
<p>Gah! The Trailing Comma of Death found its way into the code! That&#8217;s OK though, surely Stan tested in IE before he dropped his code, right? Well&#8230;..Stan had a deadline, and his thought patterns were something along the lines of this:</p>
<blockquote><p>&#8220;Oh crap, the build is about to kickoff. If I want to get this code in, I need to commit it now. It&#8217;s just a little function refactor, how could that not work in IE? I better test it though&#8230;.. Oh man, IE is so slow, it&#8217;s going to take me 15 minutes to test this&#8230;. Forget it. Let me verify it real quick in Firefox. Yup, it works. It&#8217;ll work in IE, I just know it.&#8221; *CLICK*</p></blockquote>
<p>And with that, the Trailing Comma of Death was committed to the source code repository.  The build ran that night and was first picked up by Stan&#8217;s colleagues in the UK. The build failed violently in Internet Explorer. As Stan slept, a British colleague of his was forced to investigate the failure and checked the commit history of the previous day.  Stan&#8217;s colleague, who was no stranger to the Trailing Comma of Death, found the problem and delivered a fix. When Stan checked his email that morning, he found a note in his inbox. The note was short and painful:</p>
<blockquote><p>Hey Stan. Your commit broke the build.<br />
Watch out for those trailing commas.</p>
<p>-[Name redacted]</p></blockquote>
<h2>Defending Against the Trailing Comma</h2>
<p>Trailing Commas are no joke. As Stan learned the hard way, they are <strong>extremely</strong> easy to introduce. And when working on a large and complex JavaScript application, they can be increasingly hard to find and troubleshoot.  Oh, and as Stan also learned, there are few things that Development Managers hate more than bugs introduced by trailing commas!</p>
<p>So how do we make sure that they never make it into the code in the first place? Sadly, there is no magic bullet here. The best way to stop trailing commas is a two-pronged approach of disciplined programming and configuring your development tools to flag them.  The discipline part is easy; always validate in IE while developing.  I know that IE&#8217;s Developer Tools are not the best, but that&#8217;s no excuse. As developers, each day is filled with temptations to take short-cuts. Skipping IE testing is a short-cut that you can&#8217;t afford to take.</p>
<p>On the tools front, my preference for combating these devils is the <a href="http://www.eclipse.org/webtools/jsdt/" target="_blank">Eclipse JavaScript Development Tools</a>. The JavaScript source  editor in JSDT flags trailing commas as errors:<br />
<a href="http://www.enterprisedojo.com/wp-content/uploads/2010/12/jsdtRules.png"><img class="alignnone size-full wp-image-951" style="border: 1px solid lightgrey; padding: 6px; margin: 8px 0;" title="jsdtRules" src="http://www.enterprisedojo.com/wp-content/uploads/2010/12/jsdtRules.png" alt="" width="519" height="342" /></a><br />
The venerable <a href="http://www.jslint.com/" target="_blank">JSLint</a> can be configured to flag them as well. The next level in protection after arming developers with tools is to add a trailing comma check to your build facility such that they can be sniffed out at build-time.  I&#8217;ve heard of home-brewed systems based on JSLint used for this purpose, but there may be other solutions out there as well.</p>
<h2>A Call for Discussion</h2>
<p>If you&#8217;ve been a JavaScript programmer for any length of time, you&#8217;ve almost certainly had a run-in or two with the Trailing Comma of Death.  Maybe you&#8217;ve developed your own tactics for defeating it? I am sure that there are tools and techniques out there that I have not heard of. I would love to hear your stories.  Please, add a comment to this post if your team has found a good solution. Together, we can help our fellow developers defeat this pesky adversary!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.enterprisedojo.com/2010/12/19/beware-the-trailing-comma-of-death/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>From Springfield to Stuttgart, an Introduction to i18n with Dojo</title>
		<link>http://www.enterprisedojo.com/2010/11/22/from-springfield-to-stuttgart-an-introduction-to-i18n-with-dojo/</link>
		<comments>http://www.enterprisedojo.com/2010/11/22/from-springfield-to-stuttgart-an-introduction-to-i18n-with-dojo/#comments</comments>
		<pubDate>Mon, 22 Nov 2010 12:37:17 +0000</pubDate>
		<dc:creator>Dan Lee</dc:creator>
				<category><![CDATA[Dojo]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.enterprisedojo.com/?p=729</guid>
		<description><![CDATA[For enterprise applications an internationalization story is not 'nice to have'; it is an absolute must. Rolling your own solution for i18n concerns is not out of the realm of possibilities for a good team of developers, but it's certainly not something you want to do if you can avoid it. Dojo provides a battle-tested and elegant solution for i18n out-of-the-box.  Use it.]]></description>
			<content:encoded><![CDATA[<link rel="stylesheet" href="/postresources/homeri18n/widgets/motivational/themes/Homer.css" type="text/css">
<link rel="stylesheet" href="/postresources/customwidgets/customWidgetsDemo.css" type="text/css">
<p><script src="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js" type="text/javascript" djconfig="isDebug: false, parseOnLoad: true, baseUrl: './'"></script><br />
<script src="/postresources/homeri18n/blogsetup.js" type="text/javascript" ></script> </p>
<p>A couple weeks ago I was walking back from the break-room when the words every Enterprise Developer fears came from my boss&#8217;s office.</p>
<p><em>&#8220;Hey Dan. Get in here. I&#8217;ve got an idea&#8221;.</em></p>
<p>Nervously, I walked into his office and replied, <em>&#8220;Sure, what&#8217;s up?&#8221;</em></p>
<p><em>&#8220;Well, I read a book this weekend and it really got me thinking.&#8221;</em></p>
<p>My heart skipped a beat. This was going downhill fast.</p>
<p><em>&#8220;This book talked about the role of psychology when it comes to salesmanship. It quoted a study where salespeople described their mood at 9am every morning. Do you know what they found? They found that when a salesperson described their mood as &#8216;inspired&#8217;, they sold an average of 23% more stuff! Can you believe that?!&#8221;</em></p>
<p><em>&#8220;That&#8217;s pretty cool&#8221;</em>, I said.</p>
<p><em></p>
<p>&#8220;Yeah, I know. I want you to add a feature to the Global Sales App to display some sort of inspirational quotation whenever someone on the sales team logs in! If we can get even close to what this book was saying, we&#8217;ll make a killing. Why are you standing there? Get to it!&#8221;</p>
<p></em></p>
<h2>The motivational Dojo widget</h2>
<p>I wasn&#8217;t in love with my boss&#8217;s idea, but it certainly wasn&#8217;t the worst one he&#8217;d ever had. Plus, I would get to implement this feature with Dojo. And whenever I get to use Dojo, I get excited. (This is the level of excitement that I&#8217;m talking about. Just replace the words &#8220;NINTENDO Sixty-FOOOOOOOOOOUR!!!!&#8221; with &#8220;DOJOOOOOOOOOO!!!!&#8221;).</p>
<p>
<object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/pFlcqWQVVuU?fs=1&amp;hl=en_US&amp;rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/pFlcqWQVVuU?fs=1&amp;hl=en_US&amp;rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object>
</p>
<p> I pondered a bit as to whom these motivational quotes should come from. I considered Gandhi, Sun Tzu, and other great thinkers, but after a little more thought, the answer became obvious. This man has spoken more motivational phrases than any other in contemporary times. I speak, of course, of Homer J. Simpson.</p>
<h2>The Dojo Widget</h2>
<p>After an hour or so, I had a pretty good looking widget. Here it is:</p>
<div class="widgetsInWordpress" dojoType="widgets.motivational.Homer"></div>
<p>And here is the code. Remember, Dojo widgets typically consist of three elements: an HTML fragment that holds the actual markup of the widget, a CSS file that contains the widget&#8217;s styling information, and a JavaScript file that declares the widget and defines its logic. (If you aren&#8217;t familiar with the components of custom Dojo widgets, it would be a fine time to have a look at my <a target="_blank" href="http://www.enterprisedojo.com/2010/09/21/introduction-to-custom-dojo-widgets/">Introduction to Custom Dojo Widgets</a> article).</p>
<p>The HTML template (Homer.html)</p>
<pre class="brush: xml; title: ; notranslate">
&lt;div class=&quot;homer&quot;&gt;
	&lt;div dojoattachpoint=&quot;messageHeading&quot; class=&quot;message heading&quot;&gt;&lt;/div&gt;
	&lt;div dojoattachpoint=&quot;message&quot; class=&quot;message&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
</pre>
<p>The CSS file (Homer.css)</p>
<pre class="brush: css; title: ; notranslate">
.homer {
	background: url(&quot;homer.png&quot;) no-repeat #4EA235;
	min-height: 230px;
	width: 500px;
	font : bold 18px &quot;Helvetica Neue&quot;,Arial,Sans-serif;
}

.homer .message {
	color: #FFFFFF;
	margin-left : 160px;
}

.homer .heading {
	padding: 20px 0 20px 0;
}
</pre>
</p>
<p>The JavaScript (Homer.js)</p>
<pre class="brush: jscript; title: ; notranslate">
dojo.provide(&quot;widgets.motivational.Homer&quot;);

dojo.require(&quot;dijit._Widget&quot;);
dojo.require(&quot;dijit._Templated&quot;);

dojo.declare(&quot;widgets.motivational.Homer&quot;, [ dijit._Widget, dijit._Templated ], {
    templateString : dojo.cache(&quot;widgets.motivational&quot;,
    		                    &quot;templates/Homer.html&quot;),

    postCreate : function() {
    	this.messageHeading.innerHTML =
    		&quot;Today's Motivational Message:&quot;;
    	this.message.innerHTML =
    		'&quot;You tried your best and you failed miserably. The lesson is: Never try.&quot;';
    }
});
</pre>
</p>
<p>Here is the layout of these files on disk:<br />
<a href="http://www.enterprisedojo.com/wp-content/uploads/2010/11/Screen-shot-2010-11-14-at-9.50.17-PM.png"><img src="http://www.enterprisedojo.com/wp-content/uploads/2010/11/Screen-shot-2010-11-14-at-9.50.17-PM.png" alt="" title="Screen shot 2010-11-14 at 9.50.17 PM" width="191" height="137" class="aligncenter size-full wp-image-763" /></a></p>
<p>I was about to show my boss my progress when he enthusiastically burst into my cube.</p>
<p><em>&#8220;Dan! Great news. I just got off the phone with our European Sales Team and they love my idea! Whatever you&#8217;re working on, make sure you make a German, French, and Dutch version of it too!&#8221;</em></p>
<p><em>&#8220;Oh. Awesome!&#8221;,</em> I said, matching his enthusiasm. <em>&#8220;I&#8217;m on it.&#8221;</em></p>
<p>Nobody is a fan of having more work added to their plate at the last minute, but this request was not going to be a problem. Dojo provides built-in support for internationalization, so this was going to be a snap. In fact, it&#8217;s so easy I&#8217;ll take a break from my riveting corporate software development story and explain the basics of using Dojo to provide internationalization (which is often abbreviated i18n). </p>
<h2>i18n with Dojo: Externalizing the strings</h2>
<p>The first step in internationalizing a Dojo module is to create a folder called <em>nls</em> in the root folder of the module. Inside this folder, we place one or more files that contain all of the strings that require translation.  As a convention, we can create one file for each widget in the module and name these files the same name as our widget&#8217;s JavaScript file, but they can be named anything and organized in any way that you see fit. In our case, we will create a single file named <em>Homer.js</em>. </p>
<p>The contents of this file are a JavaScript object literal containing all of the strings that require translation.  Thus the contents of <em>nls/Homer.js</em> are:</p>
<pre class="brush: jscript; title: ; notranslate">
{
	&quot;messageHeading&quot; : &quot;Today's Motivational Message:&quot;,
	&quot;message&quot; :
	        '&quot;You tried your best and you failed miserably. The lesson is: Never try.&quot;'
}
</pre>
<p>In Dojo parlance the above file is called a language <em>bundle</em>.  This particular bundle (which contains the English versions of our strings) is called the <em>default translation bundle</em> and will get fetched whenever a more specific language is not available. (More details on this in a bit).</p>
<p>Inside our <em>nls</em> folder we will create a sub-folder for each language we want to support. The names of these directories need to be lowercased versions of the appropriate <a target="_blank" href="http://www.i18nguy.com/unicode/language-identifiers.html">RFC 3066 locale abbreviations</a>. For example, the abbreviation for French is <em>fr</em> and the more specific abbreviation for French as it is spoken in France is <em>fr-fr</em>. If we wanted to support Haitian French, we would create a directory called <em>fr-ht</em>.  Dojo uses the browser&#8217;s locale setting to figure out which translations to load.  If the <em>fr-fr</em> locale is detected, Dojo will attempt to load translations at <em>nls/fr</em> and <em>nls/fr-fr</em>. The idea here is that you can put all of the strings common to the french locale in <em>nls/fr</em> and any strings specific to the France dialect in <em>fr-fr</em>.  </p>
<p>In this particular instance, dialects are not a big concern. We will simply create folders for German, French, and Dutch, placing a translated version of our <em>Homer.js</em> bundle in each. We don&#8217;t need to create folders for English, as the English cases will be handled by the default bundle in the root of the <em>nls</em> directory.</p>
<p><a href="http://www.enterprisedojo.com/wp-content/uploads/2010/11/NLSStructure.png"><img src="http://www.enterprisedojo.com/wp-content/uploads/2010/11/NLSStructure.png" alt="" title="NLSStructure" width="484" height="271" class="aligncenter size-full wp-image-821" /></a></p>
<p>The contents of the bundle files are identical to the English version, but the values of the JavaScript object are UTF-8 encoded translations of the strings.</p>
<p><em>nls/de/Homer.js</em></p>
<pre class="brush: jscript; title: ; notranslate">
{
	&quot;messageHeading&quot; : &quot;Die heutige Motivation Nachricht:&quot;,
	&quot;message&quot; :
		'&quot;Sie haben versucht, Ihre besten und Sie scheiterte kläglich. Die Lektion ist: Niemals versuchen.&quot;'
}
</pre>
<p><em>nls/fr/Homer.js</em></p>
<pre class="brush: jscript; title: ; notranslate">
{
	&quot;messageHeading&quot; : &quot;Message de motivation d'aujourd'hui:&quot;,
	&quot;message&quot; :
		'&quot;Vous avez essayé de votre mieux et vous avez échoué misérablement. La leçon est la suivante: Ne jamais essayer.&quot;'
}
</pre>
<p><em>nls/nl/Homer.js</em></p>
<pre class="brush: jscript; title: ; notranslate">
{
	&quot;messageHeading&quot; : &quot;Motiverende boodschap van vandaag:&quot;,
	&quot;message&quot; :
		'&quot;Je hebt geprobeerd je best en je mislukte jammerlijk. De les is: probeer nooit.&quot;'
}
</pre>
<p><em>Editor&#8217;s Note: I used Google Translate to come up with these translations, so they probably aren&#8217;t very good. If any European Dojo enthusiasts have stumbled across this post and would like to help provide more authentic translations, please let me know!</em></p>
<h2>Dojo APIs for Loading Externalized Strings</h2>
<p>Now that we have our strings externalized, we can modify our widget to use the appropriate translation instead of hard-coding English strings.  First, we have to load Dojo&#8217;s core i18n module. Like any Dojo module we load this with a call to <code>dojo.require</code>:</p>
<pre class="brush: jscript; title: ; notranslate">
dojo.require(&quot;dojo.i18n&quot;);
</pre>
<p>Next, we have to tell Dojo to load the appropriate language bundle. This is accomplished with a call to <code>dojo.requireLocalization</code>. This API is very similar to <code>dojo.require</code>.  The first argument is the name of the module where the language bundle lives, and the second argument is the name of the bundle itself. In our case, the name of the module is <code>widgets.Motivational</code> and the language bundle is in a file called <em>Homer.js</em>. Thus the call to <code>dojo.requireLocalization</code> looks like:</p>
<pre class="brush: jscript; title: ; notranslate">
dojo.requireLocalization(&quot;widgets.motivational&quot;, &quot;Homer&quot;);
</pre>
<p>Lastly, we will replace the occurrences of our English strings in our widget with calls to a <code>dojo.getLocalization</code>. Just like <code>dojo.requireLocalization</code>, the arguments to <code>dojo.getLocalization</code> are the name of the module followed by the name of language bundle. This API returns the actual JavaScript object literal that we defined in our language bundle files. So once we have that object, we can access our strings using regular JavaScript object &#8216;dot&#8217; notation. Thus, the original code from the <code>postCreate</code> function of our widget:</p>
<pre class="brush: jscript; title: ; notranslate">
    	this.messageHeading.innerHTML =
    		&quot;Today's Motivational Message:&quot;
    	this.message.innerHTML =
    		'&quot;You tried your best and you failed miserably. The lesson is: Never try.&quot;'
</pre>
<p>becomes:</p>
<pre class="brush: jscript; title: ; notranslate">
    	var localization =
    		dojo.i18n.getLocalization(&quot;widgets.motivational&quot;, &quot;Homer&quot;);   	

    	this.messageHeading.innerHTML = localization.messageHeading;
    	this.message.innerHTML = localization.message;
</pre>
<p>It&#8217;s as easy as that. In the future, if we want to add support for another language, all that is required would be to add a new folder and language bundle file to our <em>nls</em> folder. We will not have to modify the widget&#8217;s source code at all. Sweet.</p>
<p>Here is the internationalized widget in its entirety:</p>
<pre class="brush: jscript; title: ; notranslate">
dojo.provide(&quot;widgets.motivational.Homer&quot;);

dojo.require(&quot;dijit._Widget&quot;);
dojo.require(&quot;dijit._Templated&quot;);

dojo.require(&quot;dojo.i18n&quot;);
dojo.requireLocalization(&quot;widgets.motivational&quot;, &quot;Homer&quot;);

dojo.declare(
  &quot;widgets.motivational.Homer&quot;,
  [ dijit._Widget, dijit._Templated ],
  {
      templateString : dojo.cache(
				&quot;widgets.motivational&quot;,
				&quot;templates/Homer.html&quot;),

	  postCreate : function() {
		  var localization = dojo.i18n
				.getLocalization(
						&quot;widgets.motivational&quot;,
						&quot;Homer&quot;);

		  this.messageHeading.innerHTML =
                  localization.messageHeading;
		  this.message.innerHTML = localization.message;
	}
});
</pre>
<h2>Testing our Translations</h2>
<p>One way to test would be to painstakingly launch our web browser in each of the locales. A more convenient technique though is to take advantage of the locale setting in Dojo&#8217;s <code>djConfig</code> variable. To use it, we add it to the <code>djConfig</code> attribute in the script element that loads the <em>dojo.js</em> file. For example, to set the locale to <em>de</em>:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;script src=&quot;/path/to/dojo.js&quot;
        type=&quot;text/javascript&quot; djConfig=&quot;locale:'de'&quot;&gt;&lt;/script&gt;
</pre>
<p>Using the <code>djConfig</code> variable allows us to quickly assess how our widget looks in different languages.</p>
<p>Here&#8217;s how the widget looks in German:<br />
<a href="http://www.enterprisedojo.com/wp-content/uploads/2010/11/GermanHomer.png"><img src="http://www.enterprisedojo.com/wp-content/uploads/2010/11/GermanHomer.png" alt="" title="GermanHomer" width="496" height="225" class="aligncenter size-full wp-image-813" /></a></p>
<p>In French:<br />
<a href="http://www.enterprisedojo.com/wp-content/uploads/2010/11/FrenchHomer.png"><img src="http://www.enterprisedojo.com/wp-content/uploads/2010/11/FrenchHomer.png" alt="" title="FrenchHomer" width="496" height="226" class="aligncenter size-full wp-image-812" /></a></p>
<p>And In Dutch:<br />
<a href="http://www.enterprisedojo.com/wp-content/uploads/2010/11/DutchHomer.png"><img src="http://www.enterprisedojo.com/wp-content/uploads/2010/11/DutchHomer.png" alt="" title="DutchHomer" width="493" height="223" class="aligncenter size-full wp-image-811" /></a></p>
<p>The above are images. If you&#8217;d like to take a look at a real HTML representation of the widget in translated form, check out these pages. Do a &#8216;View Source&#8217; in your browser and look for the <code>djConfig</code> variable to see an example of setting a specific locale.</p>
<ul>
<li><a target="_blank" href="/postresources/homeri18n/testpages/testPageGerman.html">German Test Page</a></li>
<li><a target="_blank" href="/postresources/homeri18n/testpages/testPageFrench.html">French Test Page</a></li>
<li><a target="_blank" href="/postresources/homeri18n/testpages/testPageDutch.html">Dutch Test Page</a></li>
</ul>
<h2>Showing the Boss</h2>
<p>I had built a multinational, motivational, Homer Simpson-themed Dojo widget.  At risk of sounding too pleased with myself, I was pretty sure this was the crowning technical achievement of my development career. Surely, a raise was in my immediate future.  Curiously though, when I showed it to my boss, I didn&#8217;t get the reaction I was hoping for. I gave him a quick demo, and when I asked what he thought, he fell silent. He stared at my laptop&#8217;s screen with a blank expression on his face for a good 30 seconds and then finally muttered something along the lines of, &#8220;Dan, you&#8217;re lucky that you are good at this JavaScript stuff&#8221;, and walked out of my cube. I&#8217;m not exactly sure what he meant by this, but I think I&#8217;ll hold off on buying that boat&#8230;</p>
<h2>Conclusions</h2>
<p>As you may have come to expect from Enterprise Dojo, the examples that we show here are silly, but the concepts are serious. For enterprise applications an internationalization story is not &#8216;nice to have&#8217;; it is an absolute must. Rolling your own solution for i18n concerns is not out of the realm of possibilities for a good team of developers, but it&#8217;s certainly not something you want to do if you can avoid it. Dojo provides a battle-tested and elegant solution for i18n out-of-the-box.  Use it.</p>
<p>This article introduced the broad concepts of Dojo&#8217;s i18n support, but there is a lot more to it. Consult the <a target="_blank" href="http://www.dojotoolkit.org/reference-guide/quickstart/internationalization/index.html#quickstart-internationalization-index">official i18n Quickstart on dojotoolkit.org for more details</a>, and happy i18n&#8217;ing!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.enterprisedojo.com/2010/11/22/from-springfield-to-stuttgart-an-introduction-to-i18n-with-dojo/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Lessons in Widgetry: Binding Property Values to DOM Nodes in Templates</title>
		<link>http://www.enterprisedojo.com/2010/10/02/lessons-in-widgetry-binding-property-values-to-dom-nodes-in-templates/</link>
		<comments>http://www.enterprisedojo.com/2010/10/02/lessons-in-widgetry-binding-property-values-to-dom-nodes-in-templates/#comments</comments>
		<pubDate>Sat, 02 Oct 2010 18:21:22 +0000</pubDate>
		<dc:creator>Dan Lee</dc:creator>
				<category><![CDATA[Dojo]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[dijit]]></category>
		<category><![CDATA[dojo]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[widgets]]></category>

		<guid isPermaLink="false">http://www.enterprisedojo.com/?p=559</guid>
		<description><![CDATA[<p>We will explore how to 'bind' a widget property to a DOM node. That is, we will configure our widget to listen for changes in its properties and automatically update the relevant DOM nodes when a change occurs.</p>]]></description>
			<content:encoded><![CDATA[<link rel="stylesheet" href="/postresources/customwidgets/widgets/themes/highschool/HighSchooler.css" type="text/css">
<link rel="stylesheet" href="/postresources/customwidgets/customWidgetsDemo.css" type="text/css">
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dijit/themes/tundra/tundra.css" type="text/css">
<p><script src="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js" type="text/javascript" djconfig="isDebug: false, parseOnLoad: true, baseUrl: './'"></script><br />
<script src="/postresources/propertyBind/attributesMapDemo.js" type="text/javascript"></script></p>
<p>The <a href="http://www.enterprisedojo.com/2010/09/21/introduction-to-custom-dojo-widgets/" target="_blank">&#8216;High Schooler&#8217; widget</a> we created in my last post was fun, but incomplete.  A severe limitation of the widget was its static nature. As we all know, High Schooler&#8217;s are far from static.  I&#8217;m speaking from experience here. I went through a <strong>drastic</strong> metamorphosis as I progressed through that stage of my life. Just look at these photos from my formative years.</p>
<p><a href="http://www.enterprisedojo.com/wp-content/uploads/2010/10/polaroids.png"><img src="http://www.enterprisedojo.com/wp-content/uploads/2010/10/polaroids.png" alt="" title="polaroids" width="553" height="757" class="aligncenter size-full wp-image-634" /></a></p>
<p>(1997 was a bit of a rough year for me. I was listening to a lot of Fiona Apple. You understand).</p>
<p>Yes, High Schoolers are dynamic creatures, so our widget should account for that. We will enhance our widget such that its graphical representation can be updated on-the-fly.</p>
<h2>This Agreement is Binding</h2>
<p>We will explore how to &#8216;bind&#8217; a widget property to a DOM node. That is, we will configure our widget to listen for changes in its properties and automatically update the relevant DOM nodes when a change occurs.</p>
<p>I can already hear the Software Engineering part of your brain thinking about how you would code this solution. Something like this, right?</p>
<ul>
<li>We&#8217;ll need an event listener. We&#8217;ll listen for any changes to the widget&#8217;s properties.</li>
<li>When we get a change event, we&#8217;ll figure out which property changed.</li>
<li>Once we know what property changed, we&#8217;ll know which part of the DOM to update. We&#8217;ll then update that DOM node.</li>
</ul>
<p>You are on the right track! And in fact, Dojo contains two wonderful APIs for dealing with these types of situations. <a href="http://dojotoolkit.org/reference-guide/dojo/connect.html#dojo-connect" target="_blank">dojo.connect</a> is a general event handling mechanism and <a href="http://dojotoolkit.org/reference-guide/dojo/publish.html#dojo-publish" target="_blank">dojo.publish/dojo.subscribe</a> is a lightweight publication/subscription mechanism that allows us to model this pattern in a loosely coupled fashion. Both of these APIs belong in your toolbox and will be covered in future Enterprise Dojo articles. Today we won&#8217;t be needing either, however. Binding widget properties to DOM nodes is an extremely common use-case and Dojo widgets provide native support for this scenario.</p>
<h2>Using attributeMap for Simple Bindings</h2>
<p>To review, let&#8217;s take a look at the HighSchooler widget.</p>
<div class="widgetsInWordpress" dojotype="widgets.HighSchooler" fullName="Dan Lee" grade="Freshman" stereotype="geek" hero="Linus Torvalds"></div>
<p>Here is the HTML template</p>
<pre class="brush: xml; title: ; notranslate">
&lt;div class=&quot;highSchooler&quot;&gt;
  &lt;div class=&quot;avatar&quot;&gt;
    &lt;img dojoattachpoint=&quot;imageNode&quot;&gt;&lt;/img&gt;
  &lt;/div&gt;
  &lt;div&gt;
    &lt;ul class=&quot;profile&quot;&gt;
      &lt;li&gt;&lt;span class=&quot;label&quot;&gt;Name&lt;/span&gt;
	    &lt;span dojoattachpoint=&quot;nameNode&quot;&gt;&lt;/span&gt;
	  &lt;/li&gt;
	  &lt;li&gt;&lt;span class=&quot;label&quot;&gt;Grade&lt;/span&gt;
		&lt;span dojoattachpoint=&quot;gradeNode&quot;&gt;&lt;/span&gt;
	  &lt;/li&gt;
	  &lt;li&gt;&lt;span class=&quot;label&quot;&gt;Hero&lt;/span&gt;
		  &lt;span dojoattachpoint=&quot;heroNode&quot;&gt;&lt;/span&gt;
	  &lt;/li&gt;
	&lt;/ul&gt;
  &lt;/div&gt;
&lt;/div&gt;
</pre>
<p>And its JavaScript code is as follows:</p>
<pre class="brush: jscript; title: ; notranslate">
// dojo.provide allows pages to use all of the
// types declared in this resource.
dojo.provide(&quot;widgets.HighSchooler&quot;);

// dojo.require the necessary dijit hierarchy
dojo.require(&quot;dijit._Widget&quot;);
dojo.require(&quot;dijit._Templated&quot;);

dojo.declare(&quot;widgets.HighSchooler&quot;, [ dijit._Widget,
		dijit._Templated ], {
	// Path to the template
	templateString : dojo.cache(&quot;widgets&quot;,
			&quot;templates/HighSchooler.html&quot;),

	// Widget properties
	fullName : &quot;&quot;,
	grade : &quot;&quot;,
	hero : &quot;&quot;,
	stereotype : &quot;&quot;,

	// Manipulate the widget's DOM, when ready
	postCreate : function() {
		// Using the attributes defined via dojoattachpoint
		this.nameNode.innerHTML = this.fullName;
		this.gradeNode.innerHTML = this.grade;
		this.heroNode.innerHTML = this.hero;

		// Setting the avatar to be the appropriate image
		var keys = {
			emo : &quot;emo.png&quot;,
			geek : &quot;geek.png&quot;,
			punk : &quot;punk.png&quot;
		};
		var key = keys[this.stereotype] || &quot;na.png&quot;;
		var imagePath = dojo.moduleUrl(&quot;widgets&quot;,
				&quot;themes/highschool/images/&quot; + key).toString();

		// Set the 'src' attribute on our &lt;img&gt;
		dojo.attr(this.imageNode, &quot;src&quot;, imagePath);
	}
});
</pre>
<p>Let&#8217;s take a closer look at the code that does the actual DOM manipulation for the <code>fullName</code>, <code>grade</code>, and <code>hero</code> properties:</p>
<pre class="brush: jscript; title: ; notranslate">
postCreate : function() {
		// Using the attributes defined via dojoattachpoint
		this.nameNode.innerHTML = this.fullName;
		this.gradeNode.innerHTML = this.grade;
		this.heroNode.innerHTML = this.hero;
 ...
</pre>
<p>Notice the simple relationship between the <code>fullName</code>, <code>grade</code>, and <code>hero</code> widget properties and their respective DOM nodes. In each case, the value of the property is set as the <code>innerHTML</code> on a <code>span</code> element in the template.  The problem is this code runs in the <code>postCreate</code> function of our widget.  This means that it is executed after the widget is placed in the DOM, but is never run again.  What we want to do is ensure that whenever the value of <code>fullName</code>, <code>grade</code>, or <code>hero</code> changes, the <code>innerHTML</code> of their corresponding <code>span</code> element is updated. To do this, we&#8217;ll take advantage of a slick feature provided by Dojo widgets called <code>attributeMap</code>.  </p>
<p><code>attributeMap</code> is a special property that we can optionally define in our widget&#8217;s JavaScript file that specifies relationships between widget properties and DOM nodes in the widget&#8217;s HTML template.  In <code>attributeMap</code>, we specify literal objects that contain the name of a widget property, the name of the DOM node that we are binding this property to, and a <code>type</code> field that indicates what type of relationship our property has to this DOM node. In our case, <code>fullName</code>, <code>grade</code>, and <code>hero</code> will be bound to the <code>innerHTML</code> of their respective DOM nodes. Thus our <code>attributeMap</code> property looks like this:</p>
<pre class="brush: jscript; title: ; notranslate">
    // Bind 'fullName', 'grade', and 'hero' to the
	// innerHTML of their respective DOM nodes
	attributeMap: {
		fullName : {
			node : &quot;nameNode&quot;,
			type: &quot;innerHTML&quot;
		},
		grade : {
			node : &quot;gradeNode&quot;,
			type: &quot;innerHTML&quot;
		},
		hero: {
			node: &quot;heroNode&quot;,
			type: &quot;innerHTML&quot;
		}
	}
</pre>
<p>(In addition to <code>innerHTML</code>, it is also possible to bind properties directly to an HTML attribute or to a CSS class name. See <a href="http://www.dojotoolkit.org/reference-guide/quickstart/writingWidgets.html#attributemap" target="_blank">this </a>for an example).</p>
<p>With the <code>attributeMap</code> specified, whenever <code>fullName</code>, <code>grade</code>, or <code>hero</code> are modified via calls to <code>widget.set('property', 'newPropertyValue')</code>, the <code>innerHTML</code> of the corresponding DOM node will be automatically updated to the new property value.  <em>(Note: The same behavior occurs when using the deprecated <code>widget.attr('property', 'newPropertyValue')</code>. The <code>attr</code> function is slated to go away in Dojo 2.0.  But, <strong>and this is very important</strong>, the binding behavior is not honored if one modifies the property value directly, e.g. <code>widget.property = 'newValue'</code>).</em></p>
<h2>attributeMap Bindings in Action</h2>
<p>To give a concrete example, assume we have a reference to a HighSchooler widget in the variable <code>myWidget</code>.  Setting the <code>hero</code> property to &#8216;Clyde the Glide Drexler&#8217; would be done in the following way. </p>
<pre class="brush: jscript; title: ; notranslate">
myWidget.set('hero', 'Clyde the Glide Drexler');
</pre>
<p>The innerHTML of the hero span in our widget&#8217;s DOM will be automatically updated when the above code is executed.  </p>
<p>As they say, a live demo is worth 1,000 words, so give this one a try. Changing the value of the combo will be immediately reflected in the HighSchooler widget below.<br />
I have wired the following combos to call <code>set('property', valueOfCombo)</code> on the widget below using code that looks like:</p>
<pre class="brush: jscript; highlight: [4]; title: ; notranslate">
dojo.connect(dijit.byId('idOfCombo'), &quot;onChange&quot;,
    function(newValue) {
        var widget = dijit.byId('idOfHighSchoolerWidget');
        widget.set('nameOfPropertyToSet', newValue);
    }
);
</pre>
<div class="tundra" >
<div><strong>Name:</strong> </div>
<select id="nameSelect" dojoType="dijit.form.Select">
<option value="Dan Lee">Dan Lee</option>
<option value="Thunder Dan">Thunder Dan</option>
<option value="del7479">del7479</option>
</select>
<div><strong>Grade:</strong> </div>
<select id="gradeSelect" dojoType="dijit.form.Select">
<option value="Freshman">Freshman</option>
<option value="Sophomore">Sophomore</option>
<option value="Junior">Junior</option>
<option value="Senior">Senior</option>
</select>
<div><strong>Hero:</strong> </div>
<select id="heroSelect" dojoType="dijit.form.Select" >
<option value="Linus Torvalds">Linus Torvalds</option>
<option value="Larry Bird">Larry Bird</option>
<option value="The Wu-Tang Clan">The Wu-Tang Clan</option>
</select>
<div id="danLee" class="widgetsInWordpress" dojotype="widgets.HighSchooler" fullName="Dan Lee" grade="Freshman" stereotype="geek" hero="Linus Torvalds"></div>
</div>
<h2>Beyond Simple Mappings</h2>
<p>The relationship between a widget property and its corresponding DOM representation can be more complex. The <code>stereotype</code> property in our widget is a good example. To determine which photo to use in our widget we use the value of <code>stereotype</code> to calculate the path to an image. We then set this path as the <code>src</code> attribute on the <code>img</code> element in our widget&#8217;s HTML template. Here&#8217;s the code in the <code>postCreate</code> function that quantifies the relationship:</p>
<pre class="brush: jscript; title: ; notranslate">
// Setting the avatar to be the appropriate image
var keys = {
	emo : &quot;emo.png&quot;,
	geek : &quot;geek.png&quot;,
	punk : &quot;punk.png&quot;
};
var key = keys[this.stereotype] || &quot;na.png&quot;;
var imagePath = dojo.moduleUrl(&quot;widgets&quot;,
				&quot;themes/highschool/images/&quot; + key).toString();

// Set the 'src' attribute on our &lt;img&gt;
dojo.attr(this.imageNode, &quot;src&quot;, imagePath);
</pre>
<p>This relationship cannot be specified in <code>attributeMap</code> because it requires several lines of processing code to calculate the image path, however, Dojo provide us with a convention-based approach for achieving the same goal. By specifying a function in the widget&#8217;s JavaScript file that is called<code>_set<em>PropertyName</em>Attr</code>() where &#8216;<code>PropertyName</code>&#8216; is the name of the widget&#8217;s property, this function will automatically be called anytime that <code>set('PropertyName', 'newValue')</code> is called. Thus, for our widget to take advantage of this, we remove the above code from <code>postCreate</code> and refactor it into a function called _setStereoTypeAttr:</p>
<pre class="brush: jscript; title: ; notranslate">
// Whenever set('stereotype', 'newValue') is called,
// this function will be called.
_setStereotypeAttr : function(newType) {
    // Setting the avatar to be the appropriate image
	var keys = {
		emo : &quot;emo.png&quot;,
		geek : &quot;geek.png&quot;,
		punk : &quot;punk.png&quot;
	};
	var key = keys[newType] || &quot;na.png&quot;;
	var imagePath = dojo.moduleUrl(&quot;widgets&quot;,
				&quot;themes/highschool/images/&quot; + key).toString();

	// Set the 'src' attribute on our &lt;img&gt;
	dojo.attr(this.imageNode, &quot;src&quot;, imagePath);
}
</pre>
<p>With this code in place, anytime that <code>widget.set('stereotype', 'newValue')</code> is called, our _setStereoTypeAttr function will also be called. This will ensure that the image that represents the stereotype is updated. Try it out for yourself.</p>
<div class="tundra">
<div><strong>Sterotype:</strong> </div>
<select id="steroTypeSelect" dojoType="dijit.form.Select" >
<option value="emo">Emo</option>
<option value="punk">Punk</option>
<option value="geek" selected="selected">Geek</option>
</select>
</div>
<div id="danLeeSterotype" class="widgetsInWordpress"  dojotype="widgets.HighSchooler" fullName="Dan Lee" grade="Freshman" stereotype="geek" hero="Linus Torvalds"></div>
<h2>The Whole Thing</h2>
<p>Here is the full version of our widget&#8217;s updated JavaScript file, notice that the <code>postCreate</code> function is removed completely. The relationship between the widget&#8217;s properties and its DOM nodes are specified in <code>attributeMap</code> and the <code>_setStereotypeAttr</code> function.</p>
<pre class="brush: jscript; title: ; notranslate">
dojo.provide(&quot;widgets.HighSchooler&quot;);

dojo.require(&quot;dijit._Widget&quot;);
dojo.require(&quot;dijit._Templated&quot;);

dojo.declare(&quot;widgets.HighSchooler&quot;, [ dijit._Widget,
		dijit._Templated ], {
	// Path to the template
	templateString : dojo.cache(&quot;widgets&quot;,
			&quot;templates/HighSchooler.html&quot;),

	// Widget properties
	fullName : &quot;&quot;,
	grade : &quot;&quot;,
	hero : &quot;&quot;,
	stereotype : &quot;&quot;,

    // Bind 'fullName', 'grade', and 'hero' to the
    // innerHTML of their respective DOM nodes
	attributeMap:
    dojo.delegate(dijit._Widget.prototype.attributeMap, {
		fullName : {
			node : &quot;nameNode&quot;,
			type: &quot;innerHTML&quot;
		},
		grade : {
			node : &quot;gradeNode&quot;,
			type: &quot;innerHTML&quot;
		},
		hero: {
			node: &quot;heroNode&quot;,
			type: &quot;innerHTML&quot;
		}
	}),

	// Whenever set('stereotype', 'newValue' is called,
	// this function will be called.
	_setStereotypeAttr : function(newType) {
		// Setting the avatar to be the appropriate image
		var keys = {
			emo : &quot;emo.png&quot;,
			geek : &quot;geek.png&quot;,
			punk : &quot;punk.png&quot;
		};
		var key = keys[newType] || &quot;na.png&quot;;
		var imagePath = dojo.moduleUrl(&quot;widgets&quot;,
				&quot;themes/highschool/images/&quot; + key).toString();

		// Set the 'src' attribute on our &lt;img&gt;
		dojo.attr(this.imageNode, &quot;src&quot;, imagePath);
	}
});
</pre>
<p><strong>UPDATE:</strong> I added a call to dojo.delegate in the attributeMap property to ensure that the attributeMap in _Widget is not clobbered. See Kenneth G. Franqueiro&#8217;s helpful comment for more details.</p>
<h2>Dojo is Deep</h2>
<p>I&#8217;ve been writing Dojo widgets for a few years now, but only recently discovered this technique. I was content writing my own property/DOM synchronization code, but one day I stumbled across <code>attributeMap</code> in the documentation and realized that I could have been using it all along. This tends to happen when working with Dojo. Dojo is not a &#8216;Do One Thing and Do It Well&#8217;-type toolkit. Dojo is the Staples® of JavaScript toolkits. &#8221;Dojo: Yeah, we&#8217;ve got that&#8221;. </p>
<p>With all of that excellent functionality, it often means that facilities within Dojo contain gems that aren&#8217;t plainly visible on the surface. In the fast-paced world of Enterprise software development, the pressure to meet a deadline makes finding these gems even less likely.  But one of the best things about working with JavaScript, CSS, and HTML is that it is simple and fast to get a throwaway HTML page up and running.  Whenever you are given a new assignment that involves Dojo, I encourage you do a little digging first. Create a test page, navigate to <a href="http://dojotoolkit.org/reference-guide/" target="_blank">Dojo&#8217;s reference guide</a>, and try to get the examples presented there running in your browser.  Experiment with the API, even the parts that don&#8217;t appear 100% relevant to your latest assignment. You&#8217;ll understand the subject matter better, and probably learn something that you will use later on down the road.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.enterprisedojo.com/2010/10/02/lessons-in-widgetry-binding-property-values-to-dom-nodes-in-templates/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Introduction to Custom Dojo Widgets</title>
		<link>http://www.enterprisedojo.com/2010/09/21/introduction-to-custom-dojo-widgets/</link>
		<comments>http://www.enterprisedojo.com/2010/09/21/introduction-to-custom-dojo-widgets/#comments</comments>
		<pubDate>Wed, 22 Sep 2010 00:58:01 +0000</pubDate>
		<dc:creator>Dan Lee</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[dijit]]></category>
		<category><![CDATA[dojo]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[widgets]]></category>

		<guid isPermaLink="false">http://www.enterprisedojo.com/?p=366</guid>
		<description><![CDATA[Enterprise Web Applications are full of common UI elements and functionality that are ripe to be encapsulated into a reusable widget. Lucky for you, Dojo makes this process easy. The resulting code is cohesive and modular, just the way we like it.]]></description>
			<content:encoded><![CDATA[<link rel="stylesheet" href="/postresources/customwidgets/widgets/themes/highschool/HighSchooler.css" type="text/css">
<link rel="stylesheet" href="/postresources/customwidgets/customWidgetsDemo.css" type="text/css">
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dijit/themes/tundra/tundra.css" type="text/css">
<p><script src="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js.uncompressed.js" type="text/javascript" djconfig="isDebug: false, parseOnLoad: true, baseUrl: './'"></script><br />
<script src="/postresources/customwidgets/customWidgetsDemo.js" type="text/javascript"></script></p>
<p>Programmers are drawn to Dojo for its incredible suite of user interface widgets, better known as Dijits.  If you are not familiar with the breadth of Dijits that are available the <a href="http://archive.dojotoolkit.org/nightly/dojotoolkit/dijit/themes/themeTester.html?theme=claro">Theme Tester</a> is a good place to have a look around. Any doubts that you have about whether Dojo provides a suitable suite of widgets for your web application should go away quickly after playing with the Theme Tester for a few minutes. Another invaluable resource is the <a href="http://www.dojotoolkit.org/reference-guide/dijit/index.html#dijit-index" target="_blank">Dijit Reference Guide on dojotoolkit.org </a>that shows examples of all of the widgets in the Dijit library.</p>
<h2>Custom Dojo Widgets</h2>
<p>Often lost in the shuffle is that you can write your own custom widgets in addition to using the off-the-shelf Dijits. Enterprise Web Applications are full of common UI elements and functionality that are ripe to be encapsulated into a reusable widget. Lucky for you, Dojo makes this process easy. The resulting code is cohesive and modular, just the way we like it.</p>
<p>Let&#8217;s build a simple Dojo Widget using some best practices.  Now, if this were an ordinary Enterprise-y blog, our example widget would be some kind of &#8216;business card&#8217; that showed the details of a corporate employee. But let&#8217;s be honest, corporate employees are boring. We will build a business card widget for a much cooler class of people. Who are the coolest people in the world? That&#8217;s right, high school students! </p>
<h2>Building a High School Student Widget</h2>
<p>Our widget will show a picture of a high school student and their pertinent details. I don&#8217;t know many high school students, so acquiring photographs for use in this demonstration proved challenging. It was really weird, these kids acted downright frightened when I approached them in the mall and asked if they wanted to be in a JavaScript blog. Youth these days! To solve this problem, I spoke with a renowned social anthropologist who explained to me that High School students can be classified into exactly three groups: Emo, Punk, and Geek.  </p>
<div style="padding-top:10px; padding-bottom:10px">
<a href="http://www.enterprisedojo.com/wp-content/uploads/2010/09/classifications.png"><img src="http://www.enterprisedojo.com/wp-content/uploads/2010/09/classifications.png" alt="" title="classifications" width="520" height="276" class="aligncenter size-full wp-image-401" /></a>
</div>
<p>Our finished product will look something like this 1998-era version of your author:</p>
<div style="padding-top:10px; padding-bottom:10px">
<div class="widgetsInWordpress" dojotype="widgets.HighSchooler" fullName="Dan Lee" grade="Senior" stereotype="geek" hero="Linus Torvalds"></div>
</div>
<p>(You guys would have guessed that I was an Emo, huh?)</p>
<h2>Widget Pieces</h2>
<p>A typical Dojo Widget is comprised of three files:</p>
<ul>
<li>A JavaScript file that declares the widget and defines its logic.</li>
<li>An HTML fragment file that declares the widget&#8217;s semantic markup.</li>
<li>A CSS file that defines the widget&#8217;s styling information.</li>
</ul>
<p>These files don&#8217;t have to be placed in any particular location, but we will use the same convention that Dojo uses for its widgets and set up a directory structure like this:<br />
<a href="http://www.enterprisedojo.com/wp-content/uploads/2010/09/setup.png"><img src="http://www.enterprisedojo.com/wp-content/uploads/2010/09/setup.png" alt="" title="setup" width="190" height="207" class="aligncenter size-full wp-image-409" /></a></p>
<p>Our widget will be called <code>widgets.HighSchooler</code>, and its JavaScript file will be placed in a corresponding resource located at <em>widgets/HighSchooler.js</em>.  (If you read my previous post about <a href="http://www.enterprisedojo.com/2010/08/24/writing-modular-javascript-with-dojo/" target="_blank">writing modular JavaScript with Dojo</a>, this will look familiar).  Our HTML fragment will live in a folder called <em>templates </em>and our CSS file will live in a folder called <em>themes </em>,with a sub-directory called <em>highschool</em>. The images will also be placed in the <em>themes</em> directory.</p>
<h2>The JavaScript File</h2>
<p>Let&#8217;s take a look at a stubbed version of our widget&#8217;s JavaScript file.</p>
<pre class="brush: jscript; title: ; notranslate">
dojo.provide(&quot;widgets.HighSchooler&quot;);

dojo.require(&quot;dijit._Widget&quot;);
dojo.require(&quot;dijit._Templated&quot;);

dojo.declare(&quot;widgets.HighSchooler&quot;, [ dijit._Widget, dijit._Templated ], {
    templateString : dojo.cache(&quot;widgets&quot;,
    		                    &quot;templates/HighSchooler.html&quot;),
	name : &quot;&quot;,
	grade : &quot;&quot;,
	hero : &quot;&quot;,
	stereotype : &quot;&quot;
});
</pre>
<p>Declaring a widget is straight-forward. We use <code>dojo.provide</code> to declare our namespace, use <code>dojo.require</code> to load the necessary dependencies, and then use <code>dojo.declare</code> for the actual widget definition. The first argument to <code>dojo.declare</code> is our widget&#8217;s name.  We are using the pattern of giving our widget the same name as our namespace.  The second argument is the widget&#8217;s super types.  Dojo Widgets typically define two super types, <code>dijit._Widget</code> and <code>dijit._Templated</code>.  <code>_Widget</code> provides our widget with necessary life-cycle methods, which we will soon explore. <code>_Templated</code> provides support for instantiating our widget from an HTML template.   </p>
<p>The rest of the JavaScript defines the properties and methods for our HighSchooler widget.  <code>templateString </code>is a special property that indicates where to find the HTML template file. The rest of the properties represent the meaningful fields of our HighSchooler.</p>
<h2>The CSS File</h2>
<pre class="brush: css; title: ; notranslate">
.highSchooler {
	border:1px solid #CCCCCC;
	height:165px;
	margin: 10px;
}

.highSchooler .profile {
	 list-style:none outside none;
	 font: 1.3em 'Lucida Grande',sans-serif;
}

.highSchooler .avatar {
	float: left;
	margin:5px 30px 5px 10px;
}

.highSchooler .profile .label {
	font-weight: bold;
	padding-right: 5px;
}
</pre>
<p>Nothing special here, just some styles that our widget will use. The interesting thing here is that all styling information about the widget is encapsulated into this file. If we were clever about our styling information it would be possible to implement a skinnable widget, as Dojo does with the Dijit library. (This is beyond the scope of this exercise though, our widget&#8217;s styling is rudimentary).</p>
<h2>The HTML Template</h2>
<p>This file contains the actual HTML markup of our widget. In this case, we define a div that contains an image element for the avatar and another div that contains an unordered list to display the details of our HighSchooler. Notice that the relevant CSS classes are set on the nodes of this HTML fragment.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;div class=&quot;highSchooler&quot;&gt;
  &lt;div class=&quot;avatar&quot;&gt;
    &lt;img&gt;&lt;/img&gt;
  &lt;/div&gt;
  &lt;div&gt;
    &lt;ul class=&quot;profile&quot;&gt;
	  &lt;li&gt;&lt;span class=&quot;label&quot;&gt;Name&lt;/span&gt;&lt;span&gt;&lt;/span&gt;&lt;/li&gt;
	  &lt;li&gt;&lt;span class=&quot;label&quot;&gt;Grade&lt;/span&gt;&lt;span&gt;&lt;/span&gt;&lt;/li&gt;
	  &lt;li&gt;&lt;span class=&quot;label&quot;&gt;Hero&lt;/span&gt;&lt;span&gt;&lt;/span&gt;&lt;/li&gt;
	&lt;/ul&gt;
  &lt;/div&gt;
&lt;/div&gt;
</pre>
<h2>Using dojoAttachPoint</h2>
<p>There are certain elements in the widget that we will want to manipulate with JavaScript.  In this case the elements of interest are the image tag that shows the avatar and the <code>span</code> elements next to the <em>Name</em>, <em>Grade</em>, and <em>Hero</em> labels. We&#8217;ll use an extremely cool feature of Dojo called <code>dojoattachpoint</code> to enable these elements to be programmatically manipulated. We&#8217;ll add <code>dojoattachpoint</code> attributes to each of the elements that we would like to manipulate like so:</p>
<pre class="brush: xml; highlight: [3,8,11,14]; title: ; notranslate">
&lt;div class=&quot;highSchooler&quot;&gt;
  &lt;div class=&quot;avatar&quot;&gt;
    &lt;img dojoattachpoint=&quot;imageNode&quot;&gt;&lt;/img&gt;
  &lt;/div&gt;
  &lt;div&gt;
    &lt;ul class=&quot;profile&quot;&gt;
      &lt;li&gt;&lt;span class=&quot;label&quot;&gt;Name&lt;/span&gt;
	    &lt;span dojoattachpoint=&quot;nameNode&quot;&gt;&lt;/span&gt;
	  &lt;/li&gt;
	  &lt;li&gt;&lt;span class=&quot;label&quot;&gt;Grade&lt;/span&gt;
		&lt;span dojoattachpoint=&quot;gradeNode&quot;&gt;&lt;/span&gt;
	  &lt;/li&gt;
	  &lt;li&gt;&lt;span class=&quot;label&quot;&gt;Hero&lt;/span&gt;
		  &lt;span dojoattachpoint=&quot;heroNode&quot;&gt;&lt;/span&gt;
	  &lt;/li&gt;
	&lt;/ul&gt;
  &lt;/div&gt;
&lt;/div&gt;
</pre>
<p>By adding <code>dojoattachpoint</code>, we have provided access to these DOM nodes in the widget&#8217;s JavaScript file.  A property is dynamically added to the instance of the widget whose value is the DOM node associated with the element with the <code>dojoattachpoint</code> attribute.  The name of this property is the value of the <code>dojoattachpoint </code>attribute.   For example, if we want to set the <code>innerHTML</code> of the &#8216;Name&#8217; <code>span</code> to correspond to our widget&#8217;s <code>fullName</code> property, we can do so in the widget&#8217;s JavaScript file like this:</p>
<pre class="brush: jscript; title: ; notranslate">
this.nameNode.innerHTML = this.fullName;
</pre>
<p>The rest of our widget&#8217;s DOM manipulation code follows this same pattern. One thing to point out is that we only want this code to run after the widget&#8217;s DOM is ready. Dojo provides <a href="http://www.dojotoolkit.org/reference-guide/quickstart/writingWidgets.html#life-cycle" target="_blank">lifecycle methods</a> that get called during a widget&#8217;s initialization. The lifecycle method where it is safe to make DOM manipulations is called <code>postCreate</code>. We&#8217;ll add a <code>postCreate </code>function to our widget that sets up each of the <code>span</code> elements and sets the image to the appropriate avatar based on the <code>stereotype</code> property: </p>
<pre class="brush: jscript; highlight: [2,3,4,15]; title: ; notranslate">
	postCreate : function() {
		this.nameNode.innerHTML = this.fullName;
		this.gradeNode.innerHTML = this.grade;
		this.heroNode.innerHTML = this.hero;

		var keys = {
				emo : &quot;emo.png&quot;,
				geek : &quot;geek.png&quot;,
				punk: &quot;punk.png&quot;
		};
		var key = keys[this.stereotype] || &quot;na.png&quot;;
		var imagePath = dojo.moduleUrl(&quot;widgets&quot;,
				&quot;themes/highschool/images/&quot; + key).toString();

		dojo.attr(this.imageNode, &quot;src&quot;, imagePath);
	}
</pre>
<p>That&#8217;s it! Our widget&#8217;s JavaScript is done. Here it is in its entirety with some helpful comments.</p>
<pre class="brush: jscript; title: ; notranslate">
// dojo.provide allows pages to use all of the
// types declared in this resource.
dojo.provide(&quot;widgets.HighSchooler&quot;);

// dojo.require the necessary dijit hierarchy
dojo.require(&quot;dijit._Widget&quot;);
dojo.require(&quot;dijit._Templated&quot;);

dojo.declare(&quot;widgets.HighSchooler&quot;, [ dijit._Widget,
		dijit._Templated ], {
	// Path to the template
	templateString : dojo.cache(&quot;widgets&quot;,
			&quot;templates/HighSchooler.html&quot;),

	// Widget properties
	fullName : &quot;&quot;,
	grade : &quot;&quot;,
	hero : &quot;&quot;,
	stereotype : &quot;&quot;,

	// Manipulate the widget's DOM, when ready
	postCreate : function() {
		// Using the attributes defined via dojoattachpoint
		this.nameNode.innerHTML = this.fullName;
		this.gradeNode.innerHTML = this.grade;
		this.heroNode.innerHTML = this.hero;

		// Setting the avatar to be the appropriate image
		var keys = {
			emo : &quot;emo.png&quot;,
			geek : &quot;geek.png&quot;,
			punk : &quot;punk.png&quot;
		};
		var key = keys[this.stereotype] || &quot;na.png&quot;;
		var imagePath = dojo.moduleUrl(&quot;widgets&quot;,
				&quot;themes/highschool/images/&quot; + key).toString();

		// Set the 'src' attribute on our &lt;img&gt;
		dojo.attr(this.imageNode, &quot;src&quot;, imagePath);
	}
});
</pre>
<h2>Programmatic Widget Creation</h2>
<p>OK, we&#8217;ve got everything defined. The question is, how do we get these bad-boys into a page? There are two ways to instantiate a Dojo Widget, programmatic and declarative. We&#8217;ll look at programmatic creation first. To create an instance of a widget, you simply &#8216;new&#8217; it up. Optionally you can pass the ID of a node in your page where you would like the widget to appear. Alternatively, you can use the widget&#8217;s <code>placeAt</code> function if you need more finely grained control of where it shows up.</p>
<pre class="brush: jscript; title: ; notranslate">
// Always dojo.require the resources that will be used
dojo.require(&quot;widgets.HighSchooler&quot;);

// Widget instances are almost always created inside a 'ready'
// block, as they represent DOM manipulation
dojo.ready(function() {
    // Replace the contents of the node with ID 'nodeId'
   // with our widget
    var kalEl = new widgets.HighSchooler({
        fullName:&quot;Clark Kent&quot;,
        grade:&quot;Senior&quot;,
        stereotype:&quot;geek&quot;,
        hero:&quot;Myself?&quot;}, &quot;nodeId&quot;);

    // Place our widget at the end of the node with ID 'nodeId'
    var kalEl = new widgets.HighSchooler({
        fullName:&quot;Clark Kent&quot;,
        grade:&quot;Senior&quot;,
        stereotype:&quot;geek&quot;,
        hero:&quot;Myself?&quot;});
kalEl.placeAt(&quot;nodeId&quot;, &quot;last&quot;);

});
</pre>
<p>The literal object that we pass in the constructor corresponds directly to the properties of our widget. Dojo takes care of initializing them for us. Slick!</p>
<h2>Programmatic Widget Creation In Action!</h2>
<p>Here&#8217;s a little demonstration of programmatic widget creation. I used Dojo to bind an event to the button that uses the value in the combo to programmatically create a new widget and add it to the end of the node below. When the button is clicked, this code is run. Try it out. Making Geeks is fun!</p>
<pre class="brush: jscript; title: ; notranslate">
// Get the value from the combo
var typeOfTeen = dijit.byId('highSchoolerSelect').attr('value');
var newHighSchooler = new widgets.HighSchooler({
    fullName : &quot;I was&quot;,
    grade : &quot;created&quot;,
    stereotype : typeOfTeen,
    hero : &quot;programatically&quot;});

newHighSchooler.placeAt(&quot;teensGoHere&quot;, &quot;last&quot;);
</pre>
<div class="tundra">
<select id="highSchoolerSelect" name="select" dojoType="dijit.form.Select">
<option value="emo">Emo</option>
<option value="punk">Punk</option>
<option value="geek">Geek</option>
</select>
<p><button id="createButton" dojoType="dijit.form.Button">Create High Schooler!</button>
</div>
<div class="widgetsInWordpress" id="teensGoHere" style="height:400px; overflow:auto; border:1px solid gray; margin-bottom:10px"></div>
<h2>Declarative Widget Creation</h2>
<p>Sometimes it is more convenient to specify a widget in markup.  Using markup is also a fantastic way to quickly prototype your widget as you are developing it. Dojo provides the <code>dojoType</code> attribute to facilitate this. To declare a widget using markup, you simply specify the type-name of the widget using the <code>dojoType</code> attribute, and then specify any widget properties using attributes of their own.  So if we wanted to declare a punk named Chris Jaun who&#8217;s hero is Bill Bradley, we&#8217;d do it like this.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;div dojotype=&quot;widgets.HighSchooler&quot;
       fullName=&quot;Chris Jaun&quot;
       grade=&quot;Senior&quot;
       stereotype=&quot;punk&quot;
       hero=&quot;Bill Bradley&quot;&gt;
&lt;/div&gt;
</pre>
<p>Which would get rendered like this.</p>
<div class="widgetsInWordpress" dojotype="widgets.HighSchooler" fullName="Chris Jaun" grade="Senior" stereotype="punk" hero="Bill Bradley"></div>
<p>(For all of you XHTML purists out there, <code>dojoType</code> is being deprecated in Dojo 1.6 in favor of HTML5&#8242;s data-* mechanism. Hooray for clean W3C validation scans!)</p>
<p>One thing to point out about declaring widget&#8217;s using markup is that in order to get Dojo to automatically parse the page for them, you have to set the <code>parseOnLoad</code> attribute to true in Dojo&#8217;s <a href="http://dojotoolkit.org/reference-guide/djConfig.html#djconfig" target="_blank">djConfig configuration variable</a>.</p>
<h2>Conclusion</h2>
<p>Like most Dojo features, custom widgets are an incredibly powerful mechanism that would be impossible to fully cover in a single blog post.  As such, expect many future Enterprise Dojo posts about this topic.  I hope that this post piqued your attention and that you are now hungry to learn more.  Check out this <a href="http://www.dojotoolkit.org/reference-guide/quickstart/writingWidgets.html" target="_blank">article in on dojotoolkit.org</a> for a more detailed look at writing your own widgets.</p>
<p>As your web application requirements get more mature, separating and organizing your presentation layer is critical.  Custom Dojo widgets enable us to create modular, reusable user interface components, something that every enterprise-caliber web application needs. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.enterprisedojo.com/2010/09/21/introduction-to-custom-dojo-widgets/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>The Four Stages of JavaScript Grief</title>
		<link>http://www.enterprisedojo.com/2010/09/09/the-four-stages-of-javascript-grief/</link>
		<comments>http://www.enterprisedojo.com/2010/09/09/the-four-stages-of-javascript-grief/#comments</comments>
		<pubDate>Thu, 09 Sep 2010 04:14:12 +0000</pubDate>
		<dc:creator>Dan Lee</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[light hearted posts]]></category>

		<guid isPermaLink="false">http://www.enterprisedojo.com/?p=291</guid>
		<description><![CDATA[The typical beginning of an Enterprise Developer's JavaScript education is involuntary in nature. In many cases an engineer with a strong background in Java, or other strongly-typed languages, is informed that their next project requires JavaScript. Like all forced actions, this will be a bumpy road. So bumpy in fact, that the Enterprise Developer will go through a grieving process as they leave behind their beloved strongly-typed language and plunge into the duck-typed world of JavaScript. This process of grief has four distinct stages.]]></description>
			<content:encoded><![CDATA[<p>The typical beginning of an Enterprise Developer&#8217;s JavaScript education is involuntary in nature. In many cases an engineer with a strong background in Java, or other strongly-typed languages, is informed that their next project requires JavaScript. Like all forced actions, this will be a bumpy road. So bumpy in fact, that the Enterprise Developer will go through a grieving process as they leave behind their beloved strongly-typed language and plunge into the duck-typed world of JavaScript. This process of grief has four distinct stages.</p>
<h1>Stage One : Doubt</h1>
<h2>Description</h2>
<p>As I discussed earlier, the <a href="http://www.enterprisedojo.com/2010/08/19/giving-javascript-a-fair-evaluation/" target="_blank">Enterprise Developer&#8217;s usual introduction to JavaScript</a> is less than stellar. Rightly so, when a developer hears that the next &#8216;Big Project&#8217; will be done in JavaScript, their first thoughts are of the skeptical variety.</p>
<h2>Symptoms</h2>
<ul>
<li>Sufferer will indicate that the prospect of using JavaScript will certainly lead to folly.</li>
<li>Sufferer will be heard saying things like, &#8220;JavaScript? Isn&#8217;t that the thing hackers use to screw up your Back button so you can&#8217;t leave a page?&#8221;</li>
</ul>
<p><a href="http://www.enterprisedojo.com/wp-content/uploads/2010/09/stage1.png"><img src="http://www.enterprisedojo.com/wp-content/uploads/2010/09/stage1.png" alt="" title="stage1" width="499" height="410" class="aligncenter size-full wp-image-293" /></a></p>
<h1>Stage Two: Hate</h1>
<h2>Description</h2>
<p>Forced to learn JavaScript, the former-Java programmer decides that their 10 years of working with Java is more than enough experience to dive right in.  Frustration of the highest order soon follows.</p>
<h2>Symptoms</h2>
<ul>
<li>Sufferer&#8217;s cubicle bookshelf is completely devoid of any books on JavaScript.</li>
<li>Sufferer has web browser tab open to W3 Schools.</li>
<li>Sufferer&#8217;s JavaScript code has been bent, battered, and forced to conform to the look-and-feel of Java.</li>
<li>Sufferer&#8217;s screams of frustration are easily heard over hum of white-noise generator.</li>
</ul>
<p><a href="http://www.enterprisedojo.com/wp-content/uploads/2010/09/stage2.png"><img src="http://www.enterprisedojo.com/wp-content/uploads/2010/09/stage21.png" alt="" title="stage2" width="499" height="379" class="aligncenter size-full wp-image-295" /></a></p>
<h1>Stage Three: Begrudging Appreciation</h1>
<h2>Description</h2>
<p>The most important stage. If the Enterprise Developer does not <a href="http://www.boingboing.net/2010/08/25/now-you-too-can-quit.html" target="_blank">quit in spectacular fashion</a>, the only other choice is to request time from management for some much-needed JavaScript education. Once the fundamental aspects of JavaScript are learned, productive results soon follow. Our Enterprise Developer recognizes that JavaScript has some good stuff in it, has discovered a great JavaScript toolkit like <a href="http://www.dojotoolkit.org" target="_blank">Dojo</a>, and is producing efficient, cross-browser code. To be certain, the developer still <strong>hates</strong> JavaScript, however, this emotion has been put in check for the good of the project.</p>
<h2>Symptoms</h2>
<ul>
<li>Sufferer&#8217;s cubicle bookshelf contains both <a href="http://oreilly.com/catalog/9780596101992" target="_blank">JavaScript: The Definitive Guide</a> and <a href="http://oreilly.com/catalog/9780596516482" target="_blank">Dojo: The Definitive Guide</a></li>
<li>Sufferer has become proficient at debugging problems with <a href="http://getfirebug.com/" target="_blank">Firebug</a>, and cannot fathom a world without it.</li>
<li>Sufferer&#8217;s code still looks a bit Java-ish, but contains healthy doses of lambda functions, asynchronous callbacks, and other JavaScript goodies.</li>
<li>Sufferer begins to think about problem solutions in terms of JavaScript. Periodic returns to the Java world begin to feel awkward.</li>
</ul>
<p><a href="http://www.enterprisedojo.com/wp-content/uploads/2010/09/stage3.png"><img src="http://www.enterprisedojo.com/wp-content/uploads/2010/09/stage3.png" alt="" title="stage3" width="498" height="307" class="aligncenter size-full wp-image-297" /></a></p>
<h1>Stage Four: Love</h1>
<h2>Description</h2>
<p>The final stage of JavaScript grief is one of gushing adulation.  Most developers will remain indefinitely in Stage Three, but there are exceptions. The developer that reaches the &#8216;Love&#8217; stage of JavaScript Grief has completely looked past all of JavaScript&#8217;s short-comings and finds joy in its powerful concepts. </p>
<h2>Symptoms</h2>
<ul>
<li>Sufferer&#8217;s cubicle bookshelf contains nothing but JavaScript books. Directly below bookshelf, sufferer will often build a shrine to Douglas Crockford and John Resig.</li>
<li>Sufferer&#8217;s interest in JavaScript has moved beyond the browser. Sufferer will actively look for ways to add JavaScript into other parts of a software stack, usually in annoying fashion.</li>
</ul>
<p><a href="http://www.enterprisedojo.com/wp-content/uploads/2010/09/stage41.png"><img src="http://www.enterprisedojo.com/wp-content/uploads/2010/09/stage41.png" alt="" title="stage4" width="546" height="548" class="aligncenter size-full wp-image-306" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.enterprisedojo.com/2010/09/09/the-four-stages-of-javascript-grief/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 0.970 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2012-05-19 12:03:30 -->
<!-- Compression = gzip -->
