<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://devlicio.us/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Sergio Pereira : JavaScript</title><link>http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx</link><description>Tags: JavaScript</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP1 (Build: 31106.3070)</generator><item><title>Have you met arguments.callee?</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2010/09/10/have-you-met-arguments-callee.aspx</link><pubDate>Fri, 10 Sep 2010 23:36:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:62061</guid><dc:creator>sergiopereira</dc:creator><slash:comments>6</slash:comments><description>&lt;p&gt;
  Just the other day I had a need to use &lt;code&gt;arguments.callee&lt;/code&gt; and I realized that&amp;#39;s
  not something you really see every day in JavaScript. Maybe I could talk about it a bit.
 &lt;/p&gt;

 &lt;h3&gt;Anonymous functions everywhere&lt;/h3&gt;
 &lt;p&gt;
  It&amp;#39;s not news to anyone reading this blog that one of JavaScript&amp;#39;s workhorses are
  anonymous functions. Callbacks, strategies, deferred execution, event handlers, etc. 
  They just seem to be all over the place &amp;mdash; and for a good reason; they can
  be convenient and reduce the pollution of a bunch functions that are only called
  from a single spot. 
 &lt;/p&gt;
 &lt;p&gt;
  Another nice thing is that, once your eyes are trained to ignore the little bit
  of noise that they add to the code, the code is really readable and, dare I
  say it, expressive.
 &lt;/p&gt;

 &lt;h3&gt;Yet another contrived example&lt;/h3&gt;
 &lt;p&gt;
  Let&amp;#39;s say we are really into reinventing the wheel and with our understanding
  of anonymous functions we create a revolutionary &lt;code&gt;map&lt;/code&gt; function:

 &lt;/p&gt; 

 &lt;pre name="code" class="js:nogutter"&gt;function map(array, compute){
  var result = [ ];
  for(var i=0; i &amp;lt; array.length; i++){
    result.push( compute(array[i]) );
  }
  return result;
}&lt;/pre&gt;

&lt;p&gt;
	This function, as you can hopefully see, transforms each element of
	the given array into something else and returns the array of the
	transformed elements. Two simple uses are shown below.
&lt;/p&gt;

 &lt;pre name="code" class="js:nogutter"&gt;//apply discount
var prices = [1, 2, 3, 4];
var discount = 0.1; // 10% off today, w00t!
var newPrices = map(prices, function(price){ return (1-discount)*price; } );
//==&amp;gt; [0.9, 1.8, 2.7, 3.6]

//compute areas
var squareSides = [1, 2, 3, 4];
var squareAreas = map(squareSides, function(side){ return side*side; } );
//==&amp;gt; [1, 4, 9, 16]&lt;/pre&gt;

&lt;p&gt;I warned you the examples would be contrived, didn&amp;#39;t I?&lt;/p&gt;

&lt;p&gt;
	Now your product manager comes and asks for a page where the users
	can enter a list of numbers and get the factorials for each of them.
	You immediately think your friend the &lt;code&gt;map&lt;/code&gt; function will
	save the day. You start and...
&lt;/p&gt;

 &lt;pre name="code" class="js:nogutter"&gt;//return the factorials
var userNumbers = [1, 2, 3, 4];
var factorials = map(userNumbers, function(number){ 
  if(number &amp;lt;= 1) { return 1; }
  return number * ????????(number - 1); // ooops! I need to recurse here.
} );&lt;/pre&gt;

 &lt;p&gt;You see, there&amp;#39;s this thing with anonymous functions. 
 &lt;b&gt;They don&amp;#39;t have a name&lt;/b&gt;, d&amp;#39;oh. As I said in the beginning, we
 typically use them in situations where they are called only once so
 we can inline them and forego the need fora name. But now we&amp;#39;re kind of
 wishing they had a name. 

 &lt;h3&gt;Anonymity won&amp;#39;t hide you from me&lt;/h3&gt;
 &lt;p&gt;
	Well, if the post tittle didn&amp;#39;t already give it away, we can achieve that
	with 
	&lt;a href="https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments/callee"&gt;&lt;code&gt;arguments.callee&lt;/code&gt;&lt;/a&gt;. Using &lt;code&gt;arguments.callee&lt;/code&gt; inside a function gives 
	us a reference to the function itself. So now we can finish our code.
 &lt;/p&gt;
 &lt;pre name="code" class="js:nogutter"&gt;//return the factorials
var userNumbers = [1, 2, 3, 4];
var factorials = map(userNumbers, function(number){ 
  if(number &amp;lt;= 1) { return 1; }
  return number * arguments.callee(number - 1);
  //or if you were using &amp;quot;this&amp;quot; in the function you&amp;#39;ll probably want to:
  // return number * arguments.callee.apply(this, [number - 1]);
} );
//==&amp;gt; [1, 2, 6, 24]&lt;/pre&gt;

&lt;h3&gt;A more real world scenario&lt;/h3&gt;
&lt;p&gt;
I won&amp;#39;t leave you without at least a reference to a real use
case for this feature. The example I&amp;#39;ll show comes
from &lt;a href="http://www.nczonline.net/"&gt;Nicholas Zakas&lt;/a&gt;. In
&lt;a href="http://www.nczonline.net/blog/2009/08/11/timed-array-processing-in-javascript/"&gt;a blog post a while ago&lt;/a&gt; he showed how we can
break up long running tasks with smaller timed/deferred chunks,
improving the browser&amp;#39;s responsiveness.
&lt;/p&gt;

&lt;p&gt;Here&amp;#39;s the function from his blog post, which process chunks of
an array for 50ms, then stops and call itself back to process
the remaining items soon after that &amp;mdash; giving the browser
a chance to breathe and take care of its interaction with the 
user&lt;p&gt;

&lt;pre name="code" class="js:nogutter"&gt;//Copyright 2009 Nicholas C. Zakas. All rights reserved.
//MIT Licensed
function timedChunk(items, process, context, callback){
   var todo = items.concat();   //create a clone of the original

  setTimeout(function(){

    var start = +new Date();

    do {
       process.call(context, todo.shift());
    } while (todo.length &amp;gt; 0 &amp;amp;&amp;amp; (+new Date() - start &amp;lt; 50));

    if (todo.length &amp;gt; 0){
      setTimeout(arguments.callee, 25);
    } else {
      callback(items);
    }
  }, 25);
}&lt;/pre&gt;

 &lt;p&gt;I hope this shows you a little new trick.&lt;/p&gt;
&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=62061" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Tips-and-Tricks/default.aspx">Tips-and-Tricks</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript-Demystified/default.aspx">JavaScript-Demystified</category></item><item><title>Chrome Extension Development</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2010/06/28/chrome-extension-development.aspx</link><pubDate>Tue, 29 Jun 2010 03:20:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:60801</guid><dc:creator>sergiopereira</dc:creator><slash:comments>3</slash:comments><description>&lt;p&gt;Do you like JavaScript? Have you been looking for a reaon or an idea to learn and start using
HTML5? Google Chrome extesions are a great way to get into HTML5 and all its new APIs
with bite sized applications.&lt;/p&gt;

&lt;h3&gt;Anatomy of a Chrome Extension&lt;/h3&gt;

&lt;p&gt;A Chrome extesion is nothing more than a tiny website that runs hosted inside Chrome. Like
any website, it consists of regular web components. Grossly simplifying it is just a directory
full of files, such as JavaScript, CSS, images, HTML5, and anything else you usually add to
a web page.&lt;/p&gt;

&lt;p&gt;Because it runs inside the browser, you have access to things like browser events, browsing
history, and open tabs.&lt;/p&gt;

&lt;p&gt;Essentially, your extension gets loaded as an HTML page called &lt;b&gt;background.html&lt;/b&gt; where
you can put any common/global functions and variables. This page is never visible and
even if you don&amp;#39;t provide a background.html in your extension, Chrome will load an
empty one for you. All other pages in your extension can access the background page&amp;#39;s
functions.&lt;/p&gt;

&lt;p&gt;Here&amp;#39;s a diagram of a common scenario.&lt;/p&gt;

&lt;p&gt;&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2010.06/chrome_2D00_ext_2D00_diag1.png" border="0" alt="" /&gt;&lt;/p&gt;

&lt;h3&gt;Today&amp;#39;s Brew&lt;/h3&gt;

&lt;p&gt;Our sample extension will be something simple but that at the same time
will let us explore interesting aspects of extensions development, namely
local storage and cross-domain requests.&lt;/p&gt;

&lt;p&gt;The sample is also a hat tip to the valuable work &lt;a href="http://twitter.com/calcock"&gt;Chris Alcock&lt;/a&gt; does
with his &lt;a href="http://themorningbrew.net/"&gt;The Morning Brew&lt;/a&gt;, collecting some of the best links for all of us.&lt;/p&gt;

&lt;p&gt;What we will do here is create an extension that will show us his latests links at the click of a button.&lt;/p&gt;

&lt;h3&gt;Introduce yourself&lt;/h3&gt;

&lt;p&gt;The extension needs to inform Chrome a few details about itself, such as name, default icons, along with any 
permissions it requests to access privileged browser features. This is done through the &lt;b&gt;manifest file&lt;/b&gt;, which is
just a JSON document. Here&amp;#39;s our manifest file, aptly named &lt;b&gt;manifest.json&lt;/b&gt;.&lt;/p&gt;

&lt;pre name="code" class="js"&gt;{
  &amp;quot;name&amp;quot;: &amp;quot;Today&amp;#39;s Brew&amp;quot;,
  &amp;quot;version&amp;quot;: &amp;quot;1.0&amp;quot;,
  &amp;quot;description&amp;quot;: &amp;quot;Latest links from The Morning Brew.&amp;quot;,
  &amp;quot;icons&amp;quot;: { 
    &amp;quot;48&amp;quot;: &amp;quot;icon48.png&amp;quot;,
    &amp;quot;128&amp;quot;: &amp;quot;icon128.png&amp;quot; 
  },
  &amp;quot;browser_action&amp;quot;: {
    &amp;quot;default_icon&amp;quot;: &amp;quot;icon.png&amp;quot;,
    &amp;quot;default_popup&amp;quot;: &amp;quot;popup.html&amp;quot;
  },
  &amp;quot;permissions&amp;quot;: [
    &amp;quot;http://feeds.feedburner.com/&amp;quot;,
    &amp;quot;tabs&amp;quot;
  ]
}&lt;/pre&gt;

&lt;h3&gt;What you can do&lt;/h3&gt;

&lt;p&gt;Extensions can perform several different jobs, like showing notifications, providing new themes, changing
some of the default Chrome pages, etc. One other thing they can do are the browser actions, which basically 
means adding a button to the toolbar that acts independent of what page is being shown, as if it were
just another browser feature.&lt;/p&gt;

&lt;p&gt;If you look at our manifest file you&amp;#39;ll notice we declared a &lt;b&gt;browser_action&lt;/b&gt;, with its icon and the page it
opens wen clicked. &lt;/p&gt;

&lt;p&gt;Our extension does not have a custom background page, we will just rely on the default one Chrome will
give us and put all of our logic in the popup page that we will open.&lt;/p&gt;

&lt;h3&gt;What you need to do that&lt;/h3&gt;


&lt;p&gt;Here&amp;#39;s how our extension will look like when we&amp;#39;re done.
&lt;/p&gt;
&lt;p&gt;&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2010.06/todaysbrew.png" border="0" alt="" /&gt;&lt;/p&gt;

&lt;p&gt;In our extension, other than manipulating our own extension&amp;#39;s HTML dynamically (which doesn&amp;#39;t require
any special permissions) we will need to fetch the RSS feed from Feedburner and eventually open
new tabs as the user clicks on the links.&lt;/p&gt;

&lt;p&gt;That&amp;#39;s what you can see in the &lt;b&gt;permissions&lt;/b&gt; section of the manifest file above.
&lt;/p&gt;
&lt;h3&gt;Getting down to business&lt;/h3&gt;

&lt;p&gt;To create our extension we start by creating an empty directory and adding our manifest.json file and all
the icon image files that we mentioned in that manifest file.&lt;/p&gt;

&lt;p&gt;Then we create our popup.html file, which will be pretty empty and will be populated with
the content we will retrieve from the RSS feed. Here&amp;#39;s that file.&lt;/p&gt;

&lt;pre name="code" class="html:nogutter"&gt;&amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;jquery.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;popup.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;div id=&amp;quot;main&amp;quot;&amp;gt;
  &amp;lt;h1&amp;gt;&amp;lt;/h1&amp;gt;
  &amp;lt;div id=&amp;quot;content&amp;quot;&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/pre&gt;

&lt;p&gt;As you can see, we will be using jQuery so we should also add that file to our directory. We will
leave all the beautification of the popup in the popup.css file, which I won&amp;#39;t bother showing here;
you can download it along with the rest of the code at the end of this article.&lt;/p&gt;

&lt;p&gt;The other file referenced by the HTML is popup.js. That&amp;#39;s where all the action happens.
&lt;/p&gt;


&lt;pre name="code" class="js"&gt;$(document).ready(function(){
  SERGIOPEREIRA.samples.todaysBrew.init();
});

var SERGIOPEREIRA = {
  samples: {
    todaysBrew: {
      state: { },
      feedUrl: &amp;#39;http://feeds.feedburner.com/ReflectivePerspective?format=xml&amp;#39;,
      todaysUrl: &amp;#39;&amp;#39;,
      maxAgeHours: 12, // keep it for 12 hours
      
      init: function(){
        $(&amp;#39;#content h3&amp;#39;).live(&amp;#39;click&amp;#39;, function(){
          $(&amp;#39;#content ul:visible&amp;#39;).slideUp();
          $(this).next().slideToggle();
        });

        $(&amp;#39;#content li a&amp;#39;).live(&amp;#39;click&amp;#39;, function(){
          $(&amp;#39;#content ul:visible&amp;#39;).slideUp();
          chrome.tabs.create({url: this.href});
        });

        $(&amp;#39;h1&amp;#39;).click(function(){
          chrome.tabs.create({url: SERGIOPEREIRA.samples.todaysBrew.todaysUrl});
        });
        
        if(typeof chrome != &amp;#39;undefined&amp;#39;) {
          this.state = localStorage.getItem(&amp;#39;latestBrew&amp;#39;);

          if(this.state){
            var now = new Date();
            var minTimestamp = new Date();
            minTimestamp.setHours(minTimestamp.getHours() - this.maxAgeHours);
            minTimestamp = minTimestamp.toJSON();

            if(this.state.timestamp &amp;gt; minTimestamp) {
              this.renderLatest(this.state.latestData);
              return;
            }
          }
          this.refresh();
        }
      },
      refresh: function(){
        console.log(&amp;#39;will get feed data...&amp;#39;);
        $.get(this.feedUrl, function(xml, status, xhr){
          SERGIOPEREIRA.samples.todaysBrew.update(xml);
        });
      },
      update: function(feedXml) {
        var latest = this.getFirstItem(feedXml);
        this.state = { };
        this.state.latestData = latest;
        this.state.timestamp = new Date();
        localStorage[&amp;#39;latestBrew&amp;#39;] = JSON.stringify(this.state);
        this.renderLatest(latest);
      },
      renderLatest: function(latest){
        $(&amp;#39;#main&amp;gt;h1&amp;#39;).text(latest.title);
        $(&amp;#39;#content&amp;#39;).html(latest.content);
        this.todaysUrl = latest.url;
      },      
      getFirstItem: function(feedXml){
        var items = feedXml.evaluate(&amp;quot;//channel/item&amp;quot;, feedXml, 
                                 null, XPathResult.ANY_TYPE, null); 

        var item = items.iterateNext(); 
        if (item) {
          return this.createItem(item);
        }
      },      
      createItem: function(postXml) {
        return { 
          title: this.readElementText(postXml, &amp;#39;title&amp;#39;),
          url: this.readElementText(postXml, &amp;#39;feedburner:origLink&amp;#39;),
          content: this.readElementText(postXml, &amp;#39;content:encoded&amp;#39;)
        };
      },
      mapElements: function(contextElement, path, map){
        var result = [ ];
        var items = contextElement.ownerDocument.evaluate(path, contextElement, 
                                this.namespaceResolver, XPathResult.ANY_TYPE, null); 
        
        var item = items.iterateNext(); 
        var i = 0;
        while (item) {
          result.push( map(item, i++) );
          item = items.iterateNext();
        }

        return result;
      },      
      readElementText: function(contextElement, path){
        var results = contextElement.ownerDocument.evaluate(path, contextElement, 
                                   this.namespaceResolver, XPathResult.ANY_TYPE, null); 
        var first = results.iterateNext(); 

        if (first) {
          return first.textContent;
        }
      },      
      namespaceResolver: function(prefix) {
        if(prefix == &amp;#39;content&amp;#39;) {
          return &amp;#39;http://purl.org/rss/1.0/modules/content/&amp;#39;;
        }
        if(prefix == &amp;#39;feedburner&amp;#39;) {
          return &amp;#39;http://rssnamespace.org/feedburner/ext/1.0&amp;#39;;
        }
      }

    }
  }
};&lt;/pre&gt;

&lt;p&gt;Wow, that&amp;#39;s a lot of JavaScript at once, right? Hopefully you&amp;#39;ll notice that most of it is just
to parse the RSS xml.&lt;/p&gt;

&lt;p&gt;Only a few parts of this code deserve commentary. The &lt;code&gt;refresh&lt;/code&gt; method (line 45) is the one
that retrieves the RSS data. It uses the &lt;code&gt;jQuery.get&lt;/code&gt; method to do so. Once the data arrives, it will
invoke &lt;code&gt;update&lt;/code&gt;, which will use the parsing methods to get an object representing the latest
news item in the data. &lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;      update: function(feedXml) {
        var latest = this.getFirstItem(feedXml);
        this.state = { };
        this.state.latestData = latest;
        this.state.timestamp = new Date();
        localStorage[&amp;#39;latestBrew&amp;#39;] = JSON.stringify(this.state);
        this.renderLatest(latest);
      },&lt;/pre&gt;

&lt;p&gt;The above code also shows the use of two important APIs that Chrome implements. The
&lt;code&gt;localStorage&lt;/code&gt; is a way to persist information that lives in the client 
machine and lasts even after the browser closes. We use it to remeber our last
results and avoid fetching and parsing the RSS each time the popup is opened.&lt;/p&gt;

&lt;p&gt;The other API is the native &lt;code&gt;JSON&lt;/code&gt; object that can replace any dedicated
library we are used to have in cross-browser websites. We need to &lt;code&gt;stringify&lt;/code&gt;
the data because we can only save strings in the local storage.&lt;/p&gt;

&lt;p&gt;With the parsed data at hand we just need to replace the content in those empty html
tags in popup.html with the information we have.&lt;/p&gt;

&lt;h3&gt;Adding some life with events&lt;/h3&gt;

&lt;p&gt;The last piece of this puzzle are the jQuery event handlers that we created in the 
&lt;code&gt;init&lt;/code&gt; method. They make some of the elements clickable, including the
links, which open new tabs using &lt;code&gt;chrome.tabs.create()&lt;/code&gt;. Also note starting on line 
29 that if we find recent local data we use that instead of refreshing 
the content from the RSS feed.&lt;/p&gt;

&lt;h3&gt;Let&amp;#39;s load this thing up&lt;/h3&gt;

&lt;p&gt;Now we just need to run it and see how it goes. Go to the extesions page, expand
the &lt;i&gt;Developer Mode&lt;/i&gt; area and click &lt;i&gt;Load unpacked extension...&lt;/i&gt;. &lt;/p&gt;

&lt;p&gt;&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2010.06/loadext.png" border="0" alt="" /&gt;&lt;/p&gt;

&lt;p&gt;Then simply browse to your extension&amp;#39;s directory and select it. The extension should now be listed
as seen below.&lt;/p&gt;

&lt;p&gt;&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2010.06/loadedext.png" border="0" alt="" /&gt;&lt;/p&gt;

&lt;p&gt;While you&amp;#39;re developing your extension you can debug it using the developer tools
included in Chrome. To do that, right click the extension button and select 
&lt;i&gt;Inspect popup&lt;/i&gt;.&lt;/p&gt;

&lt;p&gt;You can &lt;a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2010.06/todaysbrew.zip"&gt;download&lt;/a&gt; 
the code for this extension and play with it all you want. I&amp;#39;m still early into learning this 
so feel free to give me pointers or ask questions.
&lt;/p&gt;
&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=60801" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/jQuery/default.aspx">jQuery</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/HTML5/default.aspx">HTML5</category></item><item><title>ANN: The Second Chicago Code Camp</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2010/03/22/the-second-chicago-code-camp.aspx</link><pubDate>Mon, 22 Mar 2010 17:26:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:56209</guid><dc:creator>sergiopereira</dc:creator><slash:comments>0</slash:comments><description>&lt;p&gt;After a successful first Chicago Code Camp last year, we&amp;#39;re back to announce
the second edition of this unique technical event.&lt;/p&gt;

&lt;p&gt;The &lt;a href="http://chicagocodecamp.com" title="Chicago Code Camp"&gt;Chicago Code Camp 2&lt;/a&gt;
will happen on &lt;b&gt;May 1&lt;sup&gt;st&lt;/sup&gt;&lt;/b&gt;. In this event we are addressing one obvious and
recurring feedback: &lt;b&gt;Make it closer to the city&lt;/b&gt;.&lt;/p&gt;

&lt;p&gt;We&amp;#39;re thrilled to announce that our Code Camp will take place at the 
&lt;a href="http://www.iit.edu/" title="Illinois Institute of Technology"&gt;IIT Campus&lt;/a&gt;,
just South of downtown Chicago, 
&lt;a href="http://www.iit.edu/about/directions_main.html" title="Directions to IIT&amp;#39;s Main Campus"&gt;easily accessible&lt;/a&gt; 
by car and public transportation.&lt;/p&gt;

&lt;h3&gt;What is the Chicago Code Camp?&lt;/h3&gt;

&lt;p&gt;Just like last year, we want to host an event where any platform or
programming language can have its space, as long as there&amp;#39;s community
interest in talking and hearing about it.&lt;/p&gt;

&lt;p&gt;The code camp is a great opportunity to learn about and network with
developers of different walks of life and technologies. Last year we had 
diverse topics such as .NET, Python, iPhone, Ruby, XUL, JavaScript,
Scala, etc. We hope to have even more this time around.&lt;/p&gt;

&lt;p&gt;To ensure the numerous technical communities are fairly represented, we
are inviting all local technical community leaders to get involved and
provide speakers and attendees.&lt;/p&gt;

&lt;p&gt;The event is free to attend but everyone needs to register. &lt;strike&gt;Registration will
open soon&lt;/strike&gt; &lt;a href="http://chicagocodecamp.eventbrite.com/"&gt;Registration is open&lt;/a&gt; and it&amp;#39;s limited 
due to the venue capacity.  
&lt;/p&gt;
&lt;h3&gt;Call for Speakers&lt;/h3&gt;

&lt;p&gt;The &lt;a href="http://chicagocodecamp.com" title="Chicago Code Camp 2"&gt;Chicago Code Camp&lt;/a&gt;
website is up and ready to receive talk proposals.
&lt;/p&gt;
&lt;p&gt;The &lt;a href="http://www.thedevcommunity.org/codecamps/manifesto.aspx" title="Code Camp Manifesto"&gt;Code Camp Manifesto&lt;/a&gt; calls for sessions that privilege code over 
theory or slides, but it doesn&amp;#39;t mean a good presentation will be immediately 
turned down because of that.
&lt;/p&gt;
&lt;h3&gt;Stay tuned&lt;/h3&gt;

&lt;p&gt;We will have more exciting news and announcements to share about 
this event. We will do so as soon are they are confirmed.
&lt;/p&gt;
&lt;p&gt;Keep an eye on the website (or this blog) to learn about &lt;a href="http://chicagocodecamp.eventbrite.com/"&gt;registrations&lt;/a&gt;,
volunteering, and getting involved.
&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=56209" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/.NET/default.aspx">.NET</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Ruby/default.aspx">Ruby</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Announcement/default.aspx">Announcement</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Community/default.aspx">Community</category></item><item><title>jQuery Custom Element and Global Events</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2010/02/21/jquery-custom-element-and-global-events.aspx</link><pubDate>Sun, 21 Feb 2010 18:09:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:55475</guid><dc:creator>sergiopereira</dc:creator><slash:comments>12</slash:comments><description>&lt;p&gt;This last week I learned a new thing about jQuery custom events, particularly the ones of global nature.
There&amp;#39;s good &lt;a href="http://api.jquery.com/trigger/"&gt;documentation&lt;/a&gt; 
and examples about custom element events, but
not much for the &lt;i&gt;global&lt;/i&gt; ones.&lt;/p&gt;

&lt;h3&gt;Why do we need custom events?&lt;/h3&gt;

&lt;p&gt;Custom events make it easier to keep complex pages under control. They
are a pillar for loosely-coupled UI scripts. Let&amp;#39;s start with a
simple example.&lt;/p&gt;

&lt;p&gt;Suppose we have a fairly complex and dynamic page where many elements
are Ajax-editable, using in-place editors or any other approach that 
posts updates to the server. Depending on how quickly the server 
responds to the request, there&amp;#39;s a chance the user can start another
simultaneous request before the first one finishes, maybe even seeing
inconsistent results, by clicking a button too soon.&lt;/p&gt;

&lt;p&gt;In our example &amp;mdash; a fraction of what a real complex page would be &amp;mdash; 
what we want to do is disable some of these buttons while
the data is being changed, and re-enable them once we hear back from the server.&lt;/p&gt;

&lt;pre name="code" class="html:nogutter"&gt;Click the field to edit it:&amp;lt;br&amp;gt;

&amp;lt;input type=&amp;quot;text&amp;quot; readonly=&amp;quot;readonly&amp;quot; id=&amp;quot;email&amp;quot; name=&amp;quot;email&amp;quot;
   value=&amp;quot;joe@doe.com&amp;quot; style=&amp;quot;background-color: #eee;&amp;quot;/&amp;gt; 

&amp;lt;input type=&amp;quot;button&amp;quot; class=&amp;quot;userOperation&amp;quot; id=&amp;quot;sendButton&amp;quot; value=&amp;quot;Send Message&amp;quot;&amp;gt;
&amp;lt;input type=&amp;quot;button&amp;quot; class=&amp;quot;userOperation&amp;quot; id=&amp;quot;summaryButton&amp;quot; value=&amp;quot;Summary&amp;quot;&amp;gt;&lt;/pre&gt;

&lt;h3&gt;Custom Element Events&lt;/h3&gt;

&lt;p&gt;Let&amp;#39;s tackle this problem first with the custom element events. Below is a 
summary of how these custom events are used.&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;$(&amp;#39;#publisher&amp;#39;).trigger(&amp;#39;eventName&amp;#39;);

$(&amp;#39;#publisher1&amp;#39;).bind(&amp;#39;eventName&amp;#39;, function() {
   //eventName happened. React here.
   $(&amp;#39;#subscriber1&amp;#39;).doStuff();
   $(&amp;#39;#subscriber2&amp;#39;).doOtherStuff();
   // more...
});&lt;/pre&gt;

&lt;p&gt;In this case we will make the elements being edited announce that they entered edit mode
so that any other element can act on that announcement.&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;$(&amp;#39;#email&amp;#39;).
click(function(){
	$(this).removeAttr(&amp;#39;readonly&amp;#39;).css({backgroundColor: &amp;#39;&amp;#39;});
	$(this).trigger(&amp;#39;editStart&amp;#39;);
}).
blur(function(){
	$(this).attr(&amp;#39;readonly&amp;#39;, &amp;#39;readonly&amp;#39;).css({backgroundColor: &amp;#39;#eee&amp;#39;});
	$.post(&amp;#39;/updateEmail&amp;#39;, $(&amp;#39;#email&amp;#39;).serialize(), function() {
		$(this).trigger(&amp;#39;editComplete&amp;#39;);
	});
}).
bind(&amp;#39;editStart&amp;#39;, function(){
	// &amp;quot;this&amp;quot; is the #email element
	console.log(&amp;#39;edit started, this =  &amp;#39; + this.id);
	$(&amp;#39;.userOperation&amp;#39;).attr(&amp;#39;disabled&amp;#39;, &amp;#39;disabled&amp;#39;);
}).
bind(&amp;#39;editComplete&amp;#39;, function(){
	// &amp;quot;this&amp;quot; is the #email element
	console.log(&amp;#39;edit complete, this =  &amp;#39; + this.id);
	$(&amp;#39;.userOperation&amp;#39;).removeAttr(&amp;#39;disabled&amp;#39;);		
});

$(&amp;#39;#sendButton&amp;#39;).click(function(){
	//code to send a message
	alert(&amp;#39;Message sent&amp;#39;);
});

$(&amp;#39;#summaryButton&amp;#39;).click(function(){
	//code to generate summary
	alert(&amp;#39;Summary created&amp;#39;);
});&lt;/pre&gt;


&lt;p&gt;This approach works well in the beginning but gets really ugly as
more elements need to publish their own similar events or when
other new elements need to do somethings with these events too. We
will need to bind handlers to all these element&amp;#39;s events and the code 
inside these handlers will start getting longer and probably too
far from the rest of the code that relates to it.&lt;/p&gt;

&lt;h3&gt;One step forward with page level events&lt;/h3&gt;

&lt;p&gt;Since the events we are producing here really reflect the document
state more than any individual field&amp;#39;s state, let&amp;#39;s move that event
to a more top level element, namely the &lt;code&gt;body&lt;/code&gt; element:&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;$(&amp;#39;#email&amp;#39;).
click(function(){
	$(this).removeAttr(&amp;#39;readonly&amp;#39;).css({backgroundColor: &amp;#39;&amp;#39;});
	$(&amp;#39;body&amp;#39;).trigger(&amp;#39;editStart&amp;#39;);
}).
blur(function(){
	$(this).attr(&amp;#39;readonly&amp;#39;, &amp;#39;readonly&amp;#39;).css({backgroundColor: &amp;#39;#eee&amp;#39;});
	$.post(&amp;#39;/updateEmail&amp;#39;, $(&amp;#39;#email&amp;#39;).serialize(), function() {
		$(&amp;#39;body&amp;#39;).trigger(&amp;#39;editComplete&amp;#39;);
	});
});

$(&amp;#39;body&amp;#39;).
bind(&amp;#39;editStart&amp;#39;, function(){
	// &amp;quot;this&amp;quot; is the body element
	console.log(&amp;#39;edit started, this =  &amp;#39; + this.tagName);
	$(&amp;#39;.userOperation&amp;#39;).attr(&amp;#39;disabled&amp;#39;, &amp;#39;disabled&amp;#39;);
}).
bind(&amp;#39;editComplete&amp;#39;, function(){
	// &amp;quot;this&amp;quot; is the body element
	console.log(&amp;#39;edit complete, this =  &amp;#39; + this.tagName);
	$(&amp;#39;.userOperation&amp;#39;).removeAttr(&amp;#39;disabled&amp;#39;);		
});

$(&amp;#39;#sendButton&amp;#39;).click(function(){
	//code to send a message
	alert(&amp;#39;Message sent&amp;#39;);
});

$(&amp;#39;#summaryButton&amp;#39;).click(function(){
	//code to generate summary
	alert(&amp;#39;Summary created&amp;#39;);
});&lt;/pre&gt;


&lt;p&gt;Now we&amp;#39;re getting somewhere. We reduced the number of event sources to
just one, so guaranteed less duplication. But it still has some shortcomings.&lt;/p&gt;

&lt;p&gt;The code is still bound to a different element than the one we want to operate on.
What I mean by that is that the event handlers are in the context of the elements
publishing the event and the code in the handlers is typically geared towards the
elements that need to react to that event, that is, the &lt;code&gt;this&lt;/code&gt; keyword
is less useful than in most of your common event handlers.&lt;/p&gt;

&lt;p&gt;The pattern of these page-level events is:&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;$(&amp;#39;body&amp;#39;).trigger(&amp;#39;eventName&amp;#39;);

$(&amp;#39;body&amp;#39;).bind(&amp;#39;eventName&amp;#39;, function() {
   //eventName happened. React here.
   $(&amp;#39;#subscriber1&amp;#39;).doStuff();
   $(&amp;#39;#subscriber2&amp;#39;).doOtherStuff();
   // more...
});&lt;/pre&gt;


&lt;h3&gt;But wait, jQuery has real global events too&lt;/h3&gt;

&lt;p&gt;I had settled down with using the above style of global events until
someone at work pointed out that there&amp;#39;s another way of doing this, which
unfortunately isn&amp;#39;t as well discussed: the &lt;b&gt;custom global events&lt;/b&gt;.&lt;/p&gt;

&lt;p&gt;Here&amp;#39;s our code using global custom events:&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;$(&amp;#39;#email&amp;#39;).click(function(){
	$(this).removeAttr(&amp;#39;readonly&amp;#39;).css({backgroundColor: &amp;#39;&amp;#39;});
	$.event.trigger(&amp;#39;editStart&amp;#39;);
}).blur(function(){
	$(this).attr(&amp;#39;readonly&amp;#39;, &amp;#39;readonly&amp;#39;).css({backgroundColor: &amp;#39;#eee&amp;#39;});
	$.post(&amp;#39;/updateEmail&amp;#39;, $(&amp;#39;#email&amp;#39;).serialize(), function() {
		$.event.trigger(&amp;#39;editComplete&amp;#39;);
	});
});

$(&amp;#39;.userOperation&amp;#39;).bind(&amp;#39;editStart&amp;#39;, function(){
	// &amp;quot;this&amp;quot; is a .userOperation button
	console.log(&amp;#39;edit started, button: &amp;#39; + this.id);
	$(&amp;#39;.userOperation&amp;#39;).attr(&amp;#39;disabled&amp;#39;, &amp;#39;disabled&amp;#39;);
}).bind(&amp;#39;editComplete&amp;#39;, function(){
	// &amp;quot;this&amp;quot; is a .userOperation button
	console.log(&amp;#39;edit complete, button: &amp;#39; + this.id);
	$(&amp;#39;.userOperation&amp;#39;).removeAttr(&amp;#39;disabled&amp;#39;);		
});

$(&amp;#39;#sendButton&amp;#39;).click(function(){
	//code to send a message
	alert(&amp;#39;Message sent&amp;#39;);
});

$(&amp;#39;#summaryButton&amp;#39;).click(function(){
	//code to generate summary
	alert(&amp;#39;Summary created&amp;#39;);
});&lt;/pre&gt;


&lt;p&gt;What is great about this type of event is that they are in the context
of the subscribing elements, as if these elements were the publishers of
the event, much like the majority of the event handling code we write.&lt;/p&gt;

&lt;p&gt;They also allow us to move more code next to the other event handler for
the subscribing elements, and even chain them all together. As an example,
let&amp;#39;s modify the event handlers of the &lt;code&gt;#sendButton&lt;/code&gt; element
to add some different behavior when the &lt;i&gt;editStart&lt;/i&gt; event happens.&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;$(&amp;#39;#sendButton&amp;#39;).click(function(){
	//code to send a message
	alert(&amp;#39;Message sent&amp;#39;);
}).bind(&amp;#39;editStart&amp;#39;, function(){
	// &amp;quot;this&amp;quot; is the #sendButton button
	this.value = &amp;#39;Send message (please refresh)&amp;#39;;
	// change the click event handler.
	$(this).unbind(&amp;#39;click&amp;#39;).click(function(){
		alert(&amp;#39;Sorry, refresh page before sending message&amp;#39;);
	});
});&lt;/pre&gt;

&lt;p&gt;And here is the simplified representation of the global events code.&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;$.event.trigger(&amp;#39;eventName&amp;#39;);

$(&amp;#39;#subscriber1&amp;#39;).bind(&amp;#39;eventName&amp;#39;, function() {
   //eventName happened. React here.
   $(this).doStuff();
});

$(&amp;#39;#subscriber2&amp;#39;).bind(&amp;#39;eventName&amp;#39;, function() {
   //eventName happened. React here.
   $(this).doOtherStuff();
});
//more...&lt;/pre&gt;

&lt;h3&gt;Conclusion&lt;/h3&gt;

&lt;p&gt;Event-based programming is the usual way we write UI code. By understanding 
the different types of events that jQuery provides we can allow
our UI to grow without getting into a messy nightmare of 
event handling code scattered all over the place.&lt;/p&gt;
&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=55475" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/jQuery/default.aspx">jQuery</category></item><item><title>Guided Tour: jQuery - Array wannabes</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/12/22/guided-tour-jquery-array-wannabes.aspx</link><pubDate>Wed, 23 Dec 2009 05:13:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:54712</guid><dc:creator>sergiopereira</dc:creator><slash:comments>0</slash:comments><description>	

	&lt;div class="note"&gt;
		This post is part of a series called the &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/tags/GuidedTour/default.aspx"&gt;Guided Tours&lt;/a&gt;.
	&lt;/div&gt;

	&lt;p&gt;
		In this second installment we are still looking inside the jQuery code.
		Trust me, even if it&amp;#39;s hard to digest, you can still learn enough
		if you focus on a little bit at a time.
	&lt;/p&gt;

	&lt;p&gt;
		The code we are interested in today is the following.
	&lt;/p&gt;

	&lt;pre name="code" class="js:nogutter"&gt;//from jQuery 1.3.2
get: function( num ) {
	return num === undefined ?

		// Return a &amp;#39;clean&amp;#39; array
		Array.prototype.slice.call( this ) : 

		// Return just the object
		this[ num ];
},&lt;/pre&gt;

	&lt;p&gt;
		That&amp;#39;s the code for the command &lt;code&gt;&lt;a href="http://docs.jquery.com/Core/get"&gt;jQuery.fn.get(index)&lt;/a&gt;&lt;/code&gt;, 
		which returns the element at the given index or the entire array if the index is
		omitted.
	&lt;/p&gt;

	&lt;p&gt;
		The JavaScript idiom that is really interesting in this function is that
		strangely long function call &lt;code&gt;Array.prototype.slice.call( this )&lt;/code&gt;.
	&lt;/p&gt;

	&lt;p&gt;
		That line is needed because we need to return an array and, even though they look like one, &lt;i&gt;the
		jQuery objects aren&amp;#39;t arrays&lt;/i&gt;. And they aren&amp;#39;t alone in that.
	&lt;/p&gt;

	&lt;h3&gt;If it walks like a duck...&lt;/h3&gt;

	&lt;p&gt;
		The &lt;code&gt;Array&lt;/code&gt; object is one that we can&amp;#39;t avoid becoming
		familiar with in JavaScript. They are everywhere. Data is passed
		to functions as arrays. Data is returned in arrays.
		&lt;b&gt;Or are they?&lt;/b&gt;
	&lt;/p&gt;

	&lt;p&gt;
		Aside from jQuery objects there are at least two other important occurrences
		of data structures that are used like arrays but really aren&amp;#39;t: the
		&lt;code&gt;&lt;a href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Functions_and_function_scope/arguments"&gt;arguments&lt;/a&gt;
		&lt;/code&gt; variable and the DOM &lt;code&gt;&lt;a href="https://developer.mozilla.org/En/DOM/NodeList"&gt;NodeList&lt;/a&gt;&lt;/code&gt;
		collections.
	&lt;/p&gt;

	&lt;p&gt;
		The &lt;code&gt;arguments&lt;/code&gt; variable is the list of parameters passed to 
		the current function and the &lt;code&gt;NodeList&lt;/code&gt; is what is returned from members of the the DOM API such as
		&lt;code&gt;document.getElementsByTagName()&lt;/code&gt; or &lt;code&gt;element.childNodes&lt;/code&gt;.
		Both of these types have a &lt;code&gt;length&lt;/code&gt; property and expose their
		items with indices, like &lt;code&gt;arguments[1]&lt;/code&gt; or &lt;code&gt;elements[0]&lt;/code&gt;.
	&lt;/p&gt;

	&lt;p&gt;
		But don&amp;#39;t let this small coincidence fool you. As soon as you stop paying attention
		and try to use another array method, like &lt;code&gt;push&lt;/code&gt;, &lt;code&gt;shift&lt;/code&gt;, 
		&lt;code&gt;join&lt;/code&gt; you&amp;#39;ll have your dreams shattered and a 
               &lt;code&gt;&lt;a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/TypeError"&gt;TypeError&lt;/a&gt;&lt;/code&gt;to handle.
	&lt;/p&gt;

	&lt;h3&gt;Help me, jQuery&lt;/h3&gt;

	&lt;p&gt;
		To solve the above problem and return a real array object instead of the jQuery
		object itself, the code used the technique we highlighted.
	&lt;/p&gt;

	&lt;pre name="code" class="js:nogutter"&gt;Array.prototype.slice.call( this )&lt;/pre&gt;

	&lt;p&gt;
		The idea is to use the 
		&lt;code&gt;&lt;a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/slice"&gt;array.slice()&lt;/a&gt;&lt;/code&gt;
		instance method
		to create a new array. The &lt;code&gt;slice&lt;/code&gt; method returns a chunk of the array and it
		takes two optional parameters (the boundaries) that, when omitted, make the function return
		a copy of the array itself.
	&lt;/p&gt;

	&lt;p&gt;
		I&amp;#39;ve written about the 
		&lt;code&gt;&lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/2009/06/12/javascript-not-your-father-s-inheritance-model-part-1.aspx"&gt;prototype&lt;/code&gt; 
		object&lt;/a&gt; and 
		&lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/javascript-5-ways-to-call-a-function.aspx"&gt;how to invoke functions with &lt;code&gt;call&lt;/code&gt;&lt;/a&gt; 
		in previous posts, so I won&amp;#39;t
		repeat myself here. I&amp;#39;ll just add a reminder that the &lt;code&gt;this&lt;/code&gt; object in the &lt;code&gt;get&lt;/code&gt;
		method is the jQuery instance we&amp;#39;re working with.
	&lt;/p&gt;

	&lt;p&gt;
		What&amp;#39;s going on in &lt;code&gt;call( this )&lt;/code&gt; is that &lt;code&gt;slice&lt;/code&gt; is 
		being invoked as if it was a method of the jQuery object (note: the jQuery object
		does have a method called &lt;code&gt;&lt;a href="http://docs.jquery.com/Traversing/slice"&gt;slice&lt;/a&gt;&lt;/code&gt; but it 
		does not return an array.) 
	&lt;/p&gt;
	&lt;p&gt;
		You may be wondering how can we pass a jQuery object to
		&lt;code&gt;slice.call()&lt;/code&gt; and not get any errors inside the method implementation. Well,
		it works because the &lt;code&gt;slice&lt;/code&gt; method 
               &lt;a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array#Generic_methods"&gt;was built to be generic&lt;/a&gt; and it
		only needs that the current object has a &lt;code&gt;length&lt;/code&gt; property and items
		in indexed positions. That&amp;#39;s &lt;a href="http://en.wikipedia.org/wiki/Duck_typing"&gt;Duck
		Typing&lt;/a&gt; at work.
	&lt;/p&gt;

	&lt;h3&gt;A Freebie&lt;/h3&gt;
	&lt;p&gt;
		There&amp;#39;s a small variation of this technique that you may come across in JavaScript
		as well.
	&lt;/p&gt;

	&lt;pre name="code" class="js:nogutter"&gt;[].slice.call( this )&lt;/pre&gt;

	&lt;p&gt;
		It calls the same &lt;code&gt;slice&lt;/code&gt; method but in a tad more wasteful manner
		because a new &lt;code&gt;Array&lt;/code&gt; instance is created each time just to provide access to its &lt;code&gt;slice&lt;/code&gt; method.
	&lt;/p&gt;

	&lt;p&gt;
		Well, that&amp;#39;s it. I hope you don&amp;#39;t scratch your head any longer when you see
		an expression like &lt;code&gt;XYZ.prototype.someMethod.call(obj)&lt;/code&gt; from now on.
	&lt;/p&gt;
&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=54712" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Series/default.aspx">Series</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/jQuery/default.aspx">jQuery</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/GuidedTour/default.aspx">GuidedTour</category></item><item><title>Guided Tour: jQuery - guard and default operators</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/12/09/guided-tour-jquery-guard-and-default-operators.aspx</link><pubDate>Wed, 09 Dec 2009 10:50:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:54358</guid><dc:creator>sergiopereira</dc:creator><slash:comments>5</slash:comments><description>	&lt;div class="note"&gt;
		This post is part of a series called the &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/tags/GuidedTour/default.aspx"&gt;Guided Tours&lt;/a&gt;.
	&lt;/div&gt;
	

	&lt;p&gt;I&amp;#39;m sure I&amp;#39;m not alone when I say that one of the best ways to improve our
	coding skills is by reading code written by someone else. Sometimes we
	don&amp;#39;t realize how lucky we are to have so much source code at our
	fingertips, namely Open Source Software.&lt;/p&gt;

	&lt;h3&gt;The guided tours&lt;/h3&gt;

	&lt;p&gt;With this post I&amp;#39;ll start another unbound series where I highlight 
	some interesting piece of code that I studied. I&amp;#39;ll share
	my notes and do my best to explain what I learned from it.&lt;/p&gt;

	&lt;h3&gt;jQuery: Eating the elephant one bite at a time&lt;/h3&gt;

	&lt;p&gt;I wouldn&amp;#39;t dare to start things off with a complete overview of jQuery. It&amp;#39;s
	a massive chunk of JavaScript and I&amp;#39;m afraid there isn&amp;#39;t an easy entry point
	in the source code.&lt;/p&gt;

	&lt;p&gt;I chose to find parts of it that are relatively easy to explain separately
	from the rest and that contain something worth explaining. I&amp;#39;ll do at least a
	few of those from jQuery but my plan is to not keep this series tied to
	jQuery or even JavaScript.&lt;/p&gt;

	&lt;h3&gt;The code under the microscope&lt;/h3&gt;

	&lt;p&gt;We&amp;#39;re going to take a look at &lt;code&gt;&lt;a href="http://docs.jquery.com/Attributes/text"&gt;jQuery.fn.text()&lt;/a&gt;&lt;/code&gt;,
	which returns the textual content of all the elements in the jQuery wrapped set,
	combined in a single string.&lt;/p&gt;

&lt;p&gt;	Here&amp;#39;s the code from jQuery version 1.3.2.
&lt;/p&gt;
	&lt;pre name="code" class="js:nogutter"&gt;text: function( text ) {
  if ( typeof text !== &amp;quot;object&amp;quot; &amp;amp;&amp;amp; text != null )
    return this.empty().append( 
	   (this[0] &amp;amp;&amp;amp; this[0].ownerDocument || document).createTextNode( text ) 
	);

  var ret = &amp;quot;&amp;quot;;

  jQuery.each( text || this, function(){
    jQuery.each( this.childNodes, function(){
      if ( this.nodeType != 8 )
        ret += this.nodeType != 1 ?
          this.nodeValue :
          jQuery.fn.text( [ this ] );
    });
  });

  return ret;
},&lt;/pre&gt;

	&lt;p&gt;The &lt;code&gt;text()&lt;/code&gt; function can be called with or without arguments, so 
	initially it tries to detect if a string argument was passed to it, in which
	case it will be made the content of the elements in the jQuery object.&lt;/p&gt;

	&lt;p&gt;Be aware that in all methods defined inside &lt;code&gt;jQuery.fn&lt;/code&gt; the
	value of &lt;code&gt;this&lt;/code&gt; will be the current jQuery object.&lt;/p&gt;

	&lt;p&gt;The first thing that caught my attention was the following expression:&lt;/p&gt;

	&lt;pre name="code" class="js:nogutter"&gt;(this[0] &amp;amp;&amp;amp; this[0].ownerDocument || document)&lt;/pre&gt;

	&lt;p&gt;In the context of the code it&amp;#39;s expected to return a DOM document object, but it&amp;#39;s
	a boolean expression, isn&amp;#39;t it? What gives?&lt;/p&gt;

	&lt;p&gt;Well, yes, it is a boolean expression. That leads me to explain a subtle but powerful
	difference between boolean operators in JavaScript to many other languages you may
	be more used to.&lt;/p&gt;

	&lt;h3&gt;Guard and Default operators&lt;/h3&gt;

	&lt;p&gt;The way I like to describe the boolean operators &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; and &lt;code&gt;||&lt;/code&gt;
	is: &lt;i&gt;They return the operand that short-circuited and resolved the expression.&lt;/i&gt; To
	put in a different way, when the JS interpreter detects that one of the operands has a 
	value that makes the remainder of the comparison irrelevant, it stops right there and 
	that operand (not necessarily &lt;code&gt;true&lt;/code&gt; or &lt;code&gt;false&lt;/code&gt;) becomes the
	result of the boolean expression.&lt;/p&gt;

	&lt;div class="note"&gt;&lt;span class="legend"&gt;Truthy and Falsy:&lt;/span&gt;
	In the context of a boolean expression, any value in JavaScript has a boolean meaning.
	It&amp;#39;s actually easy to memorize which mean which. The values that are treated as &lt;i&gt;false&lt;/i&gt;
	are: &lt;code&gt;false&lt;/code&gt;, &lt;code&gt;null&lt;/code&gt;, &lt;code&gt;undefined&lt;/code&gt;, &lt;code&gt;0&lt;/code&gt;, 
	&lt;code&gt;&amp;quot;&amp;quot;&lt;/code&gt; (empty string), and &lt;code&gt;NaN&lt;/code&gt;. We call them &lt;i&gt;falsy&lt;/i&gt;.
	Everything else is treated as &lt;i&gt;true&lt;/i&gt; and we call them &lt;i&gt;truthy&lt;/i&gt;.
	&lt;/div&gt;

	&lt;p&gt;Here are some examples:&lt;/p&gt;

	&lt;table&gt;
		&lt;tr&gt;&lt;td&gt;
			&lt;table border="1"&gt;
				&lt;tr&gt;&lt;th&gt;A&lt;/th&gt;&lt;th&gt;B&lt;/th&gt;&lt;th&gt;A &amp;amp;&amp;amp; B&lt;/th&gt;&lt;/tr&gt;
				&lt;tr&gt;&lt;td&gt;&lt;code&gt;false&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;123&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;&lt;code&gt;false&lt;/code&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
				&lt;tr&gt;&lt;td&gt;&lt;code&gt;null&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;123&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;&lt;code&gt;null&lt;/code&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
				&lt;tr&gt;&lt;td&gt;&lt;code&gt;0&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;123&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;&lt;code&gt;0&lt;/code&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
				&lt;tr&gt;&lt;td&gt;&lt;code&gt;undefined&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;123&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;&lt;code&gt;undefined&lt;/code&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
				&lt;tr&gt;&lt;td&gt;&lt;code&gt;undefined&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;null&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;&lt;code&gt;undefined&lt;/code&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
				&lt;tr&gt;&lt;td&gt;&lt;code&gt;123&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;null&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;&lt;code&gt;null&lt;/code&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
				&lt;tr&gt;&lt;td&gt;&lt;code&gt;123&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;456&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;&lt;code&gt;456&lt;/code&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
				&lt;tr&gt;&lt;td&gt;&lt;code&gt;123&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;&amp;quot;text&amp;quot;&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;&lt;code&gt;&amp;quot;text&amp;quot;&lt;/code&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
				&lt;tr&gt;&lt;td&gt;&lt;code&gt;&amp;quot;text&amp;quot;&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;true&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;&lt;code&gt;true&lt;/code&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
			&lt;/table&gt;
		&lt;/td&gt;
		&lt;td&gt;
			&lt;table border="1"&gt;
				&lt;tr&gt;&lt;th&gt;A&lt;/th&gt;&lt;th&gt;B&lt;/th&gt;&lt;th&gt;A || B&lt;/th&gt;&lt;/tr&gt;
				&lt;tr&gt;&lt;td&gt;&lt;code&gt;false&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;123&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;&lt;code&gt;123&lt;/code&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
				&lt;tr&gt;&lt;td&gt;&lt;code&gt;null&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;123&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;&lt;code&gt;123&lt;/code&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
				&lt;tr&gt;&lt;td&gt;&lt;code&gt;0&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;123&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;&lt;code&gt;123&lt;/code&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
				&lt;tr&gt;&lt;td&gt;&lt;code&gt;undefined&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;123&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;&lt;code&gt;123&lt;/code&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
				&lt;tr&gt;&lt;td&gt;&lt;code&gt;undefined&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;null&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;&lt;code&gt;null&lt;/code&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
				&lt;tr&gt;&lt;td&gt;&lt;code&gt;123&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;null&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;&lt;code&gt;123&lt;/code&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
				&lt;tr&gt;&lt;td&gt;&lt;code&gt;123&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;456&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;&lt;code&gt;123&lt;/code&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
				&lt;tr&gt;&lt;td&gt;&lt;code&gt;123&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;&amp;quot;text&amp;quot;&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;&lt;code&gt;123&lt;/code&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
				&lt;tr&gt;&lt;td&gt;&lt;code&gt;&amp;quot;text&amp;quot;&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;code&gt;true&lt;/code&gt;&lt;/td&gt;&lt;td&gt;&lt;b&gt;&lt;code&gt;&amp;quot;text&amp;quot;&lt;/code&gt;&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;
			&lt;/table&gt;
		&lt;/td&gt;&lt;/tr&gt;
	&lt;/table&gt;

	&lt;p&gt;Because of the above behavior, these boolean operators are often used as &lt;b&gt;Guard&lt;/b&gt; or &lt;b&gt;Default&lt;/b&gt;
	operators. The &lt;i&gt;guard&lt;/i&gt; operation is commonly used when you want to avoid a null or undefined reference error:&lt;/p&gt;

	&lt;pre name="code" class="js:nogutter"&gt;//someObj can be null. text will also be null in that case.
var text = someObj &amp;amp;&amp;amp; someObj.toString();&lt;/pre&gt;

	&lt;p&gt;Which is a shorthand for:&lt;/p&gt;

	&lt;pre name="code" class="js:nogutter"&gt;var text = null;
if (someObj !== null) {
  text = someObj.toString();
}&lt;/pre&gt;

	&lt;p&gt;The &lt;i&gt;default&lt;/i&gt; operation is arguably a much more common occurrence. We see it a lot when
	functions support optional arguments with default values. When a value is not given for
	a function parameter, it becomes &lt;code&gt;undefined&lt;/code&gt;. We can detect that and give a
	default value like this:&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;function addAll(numbersArray, step) {
  step = step || 1;
  var sum = 0;
  for (var i = 0; i &amp;lt; numbersArray.length; i += step) {
    sum += numbersArray[i];
  }
  return sum;
}
addAll([1, 2, 3, 4, 5, 6]); // ==&amp;gt; 21
addAll([1, 2, 3, 4, 5, 6], 3); // ==&amp;gt; 5&lt;/pre&gt;
	
	&lt;p&gt;In the above example, the &lt;code&gt;step&lt;/code&gt; parameter is optional. Not providing it
	would cause a problem if we hadn&amp;#39;t defaulted it to one right at the beginning of
	the function.&lt;/p&gt;

	&lt;p&gt;Wow. We sure covered a lot of stuff just to explain a simple boolean expression.
	The good news is that we will see a lot of that in the jQuery code (or in pretty
	much any decent JS code base) so it&amp;#39;s good to understand it well.&lt;/p&gt;

	&lt;p&gt;Back to our original expression.&lt;/p&gt;

	&lt;pre name="code" class="js:nogutter"&gt;(this[0] &amp;amp;&amp;amp; this[0].ownerDocument || document)&lt;/pre&gt;

	&lt;p&gt;Armed with our new understanding we can finally read this expression as:
	&lt;i&gt;If &lt;code&gt;this.ownerDocument&lt;/code&gt; exists I want that, otherwise just give me the
	global &lt;code&gt;document&lt;/code&gt; object.&lt;/i&gt; This returned DOM document object will
	be the owner document of new text value being inserted.
	&lt;/p&gt;

	&lt;h3&gt;What about the rest of that function&lt;/h3&gt;

	&lt;p&gt;It&amp;#39;s funny that a tiny bit of that function became this long post. But 
	the remainder of the function, in its majority, isn&amp;#39;t really all that interesting
	in terms of  JavaScript. It&amp;#39;s mostly boring DOM navigation, done recursively.
	If you know how to use the 
	&lt;code&gt;&lt;a href="http://docs.jquery.com/Utilities/jQuery.each"&gt;jQuery.each()&lt;/a&gt;&lt;/code&gt;
	utility function, you can figure out that code on your own.&lt;/p&gt;

	&lt;p&gt;Our time here is up and we have a whole lot more of
	code sightseeing to do.&lt;/p&gt;
&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=54358" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Series/default.aspx">Series</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/jQuery/default.aspx">jQuery</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/GuidedTour/default.aspx">GuidedTour</category></item><item><title>Test-Driving a new feature for JavaScript</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/11/12/test-driving-a-new-feature-for-javascript.aspx</link><pubDate>Fri, 13 Nov 2009 01:16:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:53698</guid><dc:creator>sergiopereira</dc:creator><slash:comments>5</slash:comments><description>&lt;/p&gt;
Earlier this week I had a piece of JavaScript that I wanted to like this:
&lt;p&gt;

&lt;pre name="code" class="js:nogutter"&gt;var index = someArray.indexOf(someObject);&lt;/pre&gt;

&lt;p&gt;
The problem there is that the &lt;code&gt;indexOf&lt;/code&gt; method of
the &lt;code&gt;Array&lt;/code&gt; object was introduced in JavaScript 1.6,
which &lt;a href="http://ejohn.org/blog/versions-of-javascript/"&gt;isn&amp;#39;t implemented in all browsers&lt;/a&gt;
(actually, IE seems to be the real problem here).
&lt;/p&gt;
&lt;p&gt;
Anyway, thanks to the awesomeness of dynamic typing and
&lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/2009/06/12/javascript-not-your-father-s-inheritance-model-part-2.aspx"&gt;prototypeal inheritance&lt;/a&gt;
in JavaScript, we can fix that ourselves with code similar to the below. 
&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(item) {
    // implementation goes here
  };
}&lt;/pre&gt;

&lt;p&gt;&lt;i&gt;Actually, if you&amp;#39;re just looking for the final solution you can
find it easily with your search engine of choice or skip to the 
&lt;a&gt;bottom of this article&lt;/a&gt;.&lt;/i&gt;&lt;/p&gt;
&lt;/p&gt;
&lt;p&gt;
But, instead of going through the normal trial and error approach,
I chose to flex my TDD muscle and try to create this method using
a test-first routine. For this exercise, I chose 
&lt;a href="http://docs.jquery.com/QUnit"&gt;QUnit&lt;/a&gt; as the unit testing framework.
&lt;/p&gt;
&lt;p&gt;
I started with a standard empty testing HTML file where I&amp;#39;ll put my test cases and
a reference to my-library.js where I&amp;#39;ll add this new method. 
&lt;/p&gt;

&lt;pre name="code" class="html:nogutter"&gt;&amp;lt;html&amp;amp;gt
  &amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;Tests for mylibrary.js&amp;lt;/title&amp;gt;
    &amp;lt;link href=&amp;quot;testsuite.css&amp;quot; rel=&amp;quot;stylesheet&amp;quot; type=&amp;quot;text/css&amp;quot; /&amp;gt;
    &amp;lt;script src=&amp;quot;jquery.js&amp;quot; type=&amp;quot;text/javascript&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script src=&amp;quot;testrunner.js&amp;quot; type=&amp;quot;text/javascript&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script src=&amp;quot;my-library.js&amp;quot; type=&amp;quot;text/javascript&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;h1&amp;gt;Tests for mylibrary.js&amp;lt;/h1&amp;gt;
    &amp;lt;h2 id=&amp;quot;banner&amp;quot;&amp;gt;
      &amp;lt;span style=&amp;quot;color:#fff;&amp;quot;&amp;gt;Result: Red/Green?&amp;lt;/span&amp;gt;
    &amp;lt;/h2&amp;gt;
    &amp;lt;h2 id=&amp;quot;userAgent&amp;quot;&amp;gt;&amp;lt;/h2&amp;gt;
    &amp;lt;ol id=&amp;quot;tests&amp;quot;&amp;gt;&amp;lt;/ol&amp;gt;
     &amp;lt;!--
        The #main element is like your test fixture. It&amp;#39;s like the 
		data for your tests.     
        Whatever exists inside the #main element gets restored 
        before each test.
        Feel free to manipulate the contents of #main in your tests.
      --&amp;gt;
    &amp;lt;div id=&amp;quot;main&amp;quot;&amp;gt;
    &amp;lt;/div&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;/pre&gt;

&lt;p&gt;
You can put your test cases in a separate .js file and reference it here but
I&amp;#39;ll just add the necessary JavaScript to the HTML file itself in this exercise.
&lt;/p&gt;
&lt;p&gt;
Here are the test cases I&amp;#39;m going to support:
&lt;/p&gt;

&lt;ol&gt;
	&lt;li&gt;Missing items return -1&lt;/li&gt;
	&lt;li&gt;Existing item is found&lt;/li&gt;
	&lt;li&gt;Existing item is found with positive starting index&lt;/li&gt;
	&lt;li&gt;Existing item is not found with positive starting index&lt;/li&gt;
	&lt;li&gt;Existing item is found with negative starting index&lt;/li&gt;
	&lt;li&gt;Existing item is not found with negative starting index&lt;/li&gt;
	&lt;li&gt;Comparison is non-coercive&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
Let&amp;#39;s start with the first test: &lt;i&gt;Missing items return -1&lt;/i&gt;. It&amp;#39;s a simple value comparison.
At this point I do not have anything written yet for the &lt;code&gt;indexOf&lt;/code&gt; function,
it doesn&amp;#39;t even exist if you&amp;#39;re on IE. Add the following to the HTML file.
&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;$(function() {
  var list = [11, 22, 33, 44];
  
  module(&amp;#39;Array.indexOf&amp;#39;);
  
  test(&amp;#39;Missing items return -1&amp;#39;, function() {
    equals(list.indexOf(1234), -1);
  });

});&lt;/pre&gt;                

&lt;p&gt;
When you open the HTML file on IE (I&amp;#39;m using IE8), you&amp;#39;ll see this:
&lt;/p&gt;
&lt;p&gt;
&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.11/tdd_2D00_qunit_2D00_1.png" alt="" /&gt;
&lt;/p&gt;
&lt;p&gt;
Totally expected, but let&amp;#39;s try to make this test pass. In the my-library.js file,
let&amp;#39;s add the simplest code that can satisfy that test.
&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function() {
      return -1;
    };
}&lt;/pre&gt;

&lt;p&gt;
The outer &lt;code&gt;if&lt;/code&gt; is there just to prevent replacing the function if
it already exists. The function is clearly incomplete, but that&amp;#39;s not the point.
The point is that it passes the test:
&lt;/p&gt;
&lt;p&gt;
&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.11/tdd_2D00_qunit_2D00_2.png" alt="" /&gt;
&lt;/p&gt;
&lt;p&gt;
Great. Time for the second test: &lt;i&gt;Existing item is found&lt;/i&gt;. For that one
we will need to loop through the items in the array. The array is &lt;code&gt;this&lt;/code&gt;
in the method. Here&amp;#39;s the test, which we add right after the first one.
&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;test(&amp;#39;Existing item is found&amp;#39;, function() {
  equals(list.indexOf(22), 1);
});&lt;/pre&gt;

&lt;p&gt;And of course that fails&lt;/p&gt;

&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.11/tdd_2D00_qunit_2D00_3.png" alt="" /&gt;
&lt;/p&gt;
&lt;p&gt;
Time to make it pass.
&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(item) {
    for (var i=0; i&amp;lt;this.length; i++) {
      if (this[i] == item) {
        return i;
      }
    }
    return -1;
  };
}&lt;/pre&gt;
		
&lt;p&gt;
And it passes:
&lt;/p&gt;
&lt;p&gt;
&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.11/tdd_2D00_qunit_2D00_4.png" alt="" /&gt;
&lt;/p&gt;
&lt;p&gt;
Now let&amp;#39;s tackle the third test case: &lt;i&gt;Existing item is found with positive starting index&lt;/i&gt;.
This one starts to make things interesting. Here&amp;#39;s the test.
&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;test(&amp;#39;Existing item is found with positive starting index&amp;#39;, function() {
  //let&amp;#39;s try a few boundary conditions
  equals(list.indexOf(33, 0), 2);
  equals(list.indexOf(33, 1), 2);
  equals(list.indexOf(33, 2), 2);
});&lt;/pre&gt;

&lt;p&gt;
Hmmm. The test passes, as we can see below. Well, that was kind of an accident but 
I&amp;#39;ll leave the test as is because it does test what was specified. Leaving the
test will help us if we make changes that break this specification.
&lt;p&gt;
&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.11/tdd_2D00_qunit_2D00_5.png" alt="" /&gt;
&lt;/p&gt;
&lt;p&gt;
The next test case is &lt;i&gt;Existing item is not found with positive starting index&lt;/i&gt;. We could 
write it like this:
&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;test(&amp;#39;Existing item is not found with positive starting index&amp;#39;, function() {
  equals(list.indexOf(33, 3), -1);
  equals(list.indexOf(33, 1000), -1);
});&lt;/pre&gt;

&lt;p&gt;
And boom! It fails. It should, we don&amp;#39;t even have support for that second parameter yet.
&lt;/p&gt;
&lt;p&gt;
&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.11/tdd_2D00_qunit_2D00_6.png" alt="" /&gt;
&lt;/p&gt;
&lt;p&gt;
Failing it is, pass it we must. First attempt:
&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(item, startIndex) {
    for (var i=startIndex; i&amp;lt;this.length; i++) {
      if (this[i] == item) {
        return i;
      }
    }
    return -1;
  };
}&lt;/pre&gt;

&lt;p&gt;
It passes the new test, but it fails another one:
&lt;/p&gt;
&lt;p&gt;
&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.11/tdd_2D00_qunit_2D00_7.png" alt="" /&gt;
&lt;/p&gt;
&lt;p&gt;
That&amp;#39;s actually pretty cool. We would have created a mess if we had just
added the second parameter without some regression testing. Hooray for
unit tests! 
&lt;/p&gt;
&lt;p&gt;
What&amp;#39;s happening is that my &lt;code&gt;startIndex&lt;/code&gt; defaults to &lt;code&gt;undefined&lt;/code&gt;
if not passed by the caller. It should default to zero. Easy fix.
&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(item, startIndex) {
    startIndex = startIndex || 0;
    for (var i=startIndex; i&amp;lt;this.length; i++) {
      if (this[i] == item) {
        return i;
      }
    }
    return -1;
  };
}&lt;/pre&gt;	

&lt;p&gt;
I see the green light!
&lt;/p&gt;
&lt;p&gt;
&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.11/tdd_2D00_qunit_2D00_8.png" alt="" /&gt;
&lt;/p&gt;
&lt;p&gt;
Our next test case is up: &lt;i&gt;Existing item is found with negative starting index&lt;/i&gt;.
What we are trying to do here is allow the caller to specify the starting position as
an offset from the last item using a negative number. So in a 4-element array, passing
-1 means that we start at the last item and passing -3 we start at the second item. See 
the test.
&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;test(&amp;#39;Existing item is found with negative starting index&amp;#39;, function() {
  equals(list.indexOf(33, -2), 2);
  equals(list.indexOf(33, -3), 2);
  equals(list.indexOf(33, -1000), 2);
});&lt;/pre&gt;

&lt;p&gt;
Once again it passes by accident. 
&lt;/p&gt;
&lt;p&gt;
&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.11/tdd_2D00_qunit_2D00_9.png" alt="" /&gt;
&lt;/p&gt;
&lt;p&gt;
The next text case will show that it was an accident:
&lt;i&gt;Existing item is not found with negative starting index&lt;/i&gt;. The test for that is below:
&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;test(&amp;#39;Existing item is not found with negative starting index&amp;#39;, function() {
  equals(list.indexOf(33, -1), -1);
  equals(list.indexOf(11, -3), -1);
});&lt;/pre&gt;


&lt;p&gt;
It fails:
&lt;/p&gt;
&lt;p&gt;
&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.11/tdd_2D00_qunit_2D00_10.png" alt="" /&gt;
&lt;/p&gt;
&lt;p&gt;
Making it pass is not that hard, we just need to compute a positive 
version of that negative start index.
&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(item, startIndex) {
    startIndex = startIndex || 0;
    
    if (startIndex &amp;lt; 0) {
      startIndex += this.length;
    }
    
    for (var i=startIndex; i&amp;lt;this.length; i++) {
      if (this[i] == item) {
        return i;
      }
    }
    return -1;
  };
}&lt;/pre&gt;	

&lt;p&gt;	
Ding, ding, ding! Another passing test for our team.
&lt;/p&gt;
&lt;p&gt;
&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.11/tdd_2D00_qunit_2D00_11.png" alt="" /&gt;
&lt;/p&gt;
&lt;p&gt;
Lastly, we need to make sure that the &lt;i&gt;Comparison is non-coercive&lt;/i&gt;. By
that we mean, a number will never equal a string &amp;mdash; or generally speaking, the
things being compared must be of the same type. Let&amp;#39;s get some tests that
try to point out tha flaw in our current code.
&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;test(&amp;#39;Comparison is non-coercive&amp;#39;, function() {
  equals(list.indexOf(&amp;#39;22&amp;#39;), -1);
});&lt;/pre&gt;

&lt;p&gt;
This fails because, strictly speaking, &lt;code&gt;22&lt;/code&gt; and &lt;code&gt;&amp;#39;22&amp;#39;&lt;/code&gt;
are two different things and we didn&amp;#39;t want to match that element like we did.
&lt;/p&gt;
&lt;p&gt;
&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.11/tdd_2D00_qunit_2D00_12.png" alt="" /&gt;
&lt;/p&gt;

&lt;p&gt;
	On to the fix. Can you spot the difference? Try harder.
&lt;/p&gt;
&lt;a name="solution"&gt;&lt;/a&gt;
&lt;pre name="code" class="js:nogutter"&gt;if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(item, startIndex) {
    startIndex = startIndex || 0;
    
    if (startIndex &amp;lt; 0) {
        startIndex += this.length;
    }
    
    for (var i=startIndex; i&amp;lt;this.length; i++) {
        if (this[i] === item) {
          return i;
        }
    }
    return -1;
  };
}&lt;/pre&gt;	

&lt;p&gt;
And here is the QUnit report in all its successful glory.
&lt;/p&gt;
&lt;p&gt;
&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.11/tdd_2D00_qunit_2D00_13.png" alt="" /&gt;
&lt;/p&gt;
&lt;p&gt;
If you&amp;#39;ve never been exposed to TDD this may have felt awkward but
hopefully you noticed that it&amp;#39;s more of an evolutionary design
approach, as opposed to trying to make it perfect on the first attempt or
even reckless patching.
&lt;/p&gt;
&lt;p&gt;
It also left us with a valuable collection of tests that we
can execute after making changes to the code, ensuring we didn&amp;#39;t
break anything by accident.
&lt;p&gt;	

&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=53698" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Development/default.aspx">Development</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/UnitTesting/default.aspx">UnitTesting</category></item><item><title>Talk: Stop Programming JavaScript by Luck</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/11/10/talk-stop-programming-javascript-by-luck.aspx</link><pubDate>Tue, 10 Nov 2009 09:07:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:53615</guid><dc:creator>sergiopereira</dc:creator><slash:comments>2</slash:comments><description>&lt;p&gt;
	Last Saturday I had the pleasure to present a JavaScript talk at the 
	&lt;a href="http://iowacodecamp.com/"&gt;Iowa Code Camp&lt;/a&gt;. The talk was
	&lt;i&gt;&lt;a href="http://www.sergiopereira.com/presentations/js-by-luck.html"&gt;Stop Programming JavaScript By Luck&lt;/a&gt;&lt;/i&gt; and it tries to
	highlight some of the most puzzling differences from your mainstream
	programming language (read: C#, VB, Java.)
&lt;/p&gt;
&lt;p&gt;
	I&amp;#39;d like to thank all that came to the talk and the Code Camp organizers
	for inviting me. Here are the video recording and the slide deck.
&lt;/p&gt;

&lt;h3&gt;The video&lt;/h3&gt;
&lt;object width="545" height="349" id="viddler_2cc7bbee"&gt;&lt;param name="movie" value="http://www.viddler.com/player/2cc7bbee/" /&gt;&lt;param name="allowScriptAccess" value="always" /&gt;&lt;param name="allowFullScreen" value="true" /&gt;&lt;embed src="http://www.viddler.com/player/2cc7bbee/" width="545" height="349" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" name="viddler_2cc7bbee"&gt;&lt;/embed&gt;&lt;/object&gt;

&lt;p&gt;&amp;nbsp;&lt;/p&gt;

&lt;h3&gt;And the slide deck.&lt;/h3&gt;

&lt;div style="width:425px;text-align:left;" id="__ss_2459675"&gt;	
	
	&lt;object style="margin:0px;" width="425" height="355"&gt;
		&lt;param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=js-by-luck-091109125553-phpapp02&amp;amp;stripped_title=stop-programming-in-javascript-by-luck" /&gt;
		&lt;param name="allowFullScreen" value="true" /&gt;
		&lt;param name="allowScriptAccess" value="always" /&gt;
		&lt;embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=js-by-luck-091109125553-phpapp02&amp;amp;stripped_title=stop-programming-in-javascript-by-luck" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"&gt;
		&lt;/embed&gt;
	&lt;/object&gt;

&lt;/div&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=53615" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Video/default.aspx">Video</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Community/default.aspx">Community</category></item><item><title>CouchDB Presentation</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/10/01/couchdb-presentation.aspx</link><pubDate>Thu, 01 Oct 2009 09:26:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:51931</guid><dc:creator>sergiopereira</dc:creator><slash:comments>0</slash:comments><description>&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.general/chicago_2D00_alt-net.png" align="left" alt="" /&gt;
&lt;p&gt;
 In this month&amp;#39;s &lt;a href="http://chicagoalt.net/"&gt;Chicago ALT.NET&lt;/a&gt; meeting we will be taking a look at
Apache &lt;a href="http://couchdb.apache.org/"&gt;CouchDB&lt;/a&gt;. I quote from the official site:
&lt;/p&gt;
&lt;blockquote&gt;
&lt;i&gt;
&lt;p&gt;
Apache CouchDB is a document-oriented database that can be queried and indexed in a MapReduce fashion using JavaScript. CouchDB also offers incremental replication with bi-directional conflict detection and resolution.
&lt;/p&gt;
&lt;p&gt;
CouchDB provides a RESTful JSON API than can be accessed from any environment that allows HTTP requests. 
&lt;/p&gt;
&lt;/i&gt;
&lt;/blockquote&gt;

&lt;h3&gt;Get Comfy With CouchDB&lt;/h3&gt;

&lt;p&gt;
		&lt;span style="font-size:x-small;"&gt;6:00 pm&lt;/span&gt; 
		&lt;br /&gt;
		Pizza and networking time
&lt;/p&gt;
&lt;p&gt;
		&lt;span style="font-size:x-small;"&gt;6:30 pm&lt;/span&gt; 
&lt;/p&gt;
&lt;img src="http://chicagoalt.net/content/images/events/couchdb.gif" align="right" alt="" /&gt;
&lt;p&gt;
	&lt;a href="http://couchdb.apache.org/"&gt;CouchDB&lt;/a&gt; is one of the more mature schema-less map/reduce 
	object dbs out there. In this talk we&amp;#39;ll cover the basics of what CouchDB is, and why it&amp;#39;s cool, 
	and then we&amp;#39;ll run through a sample application. The application will show off LINQ to Couch, 
	basic persistance, views and full-text search with CouchDB-Lucene.
&lt;/p&gt;

&lt;p&gt;
	&lt;b&gt;&lt;a href="http://www.russiantequila.com/"&gt;Alex Pedenko&lt;/a&gt;&lt;/b&gt; has been in software development for about 13 years, starting off on Borland Delphi, then spending about 4 years in Java and finally making the switch to .net around &amp;#39;03
	&lt;/p&gt;
	&lt;p&gt;Currently, he is the director of software architecture and chief architect at a healthcare services company. He has used that role as an opportunity to inject some modern ideas into an otherwise lagging industry, moving the company from a classic &amp;quot;giant web-app strapped to an even more giant db&amp;quot;, to a distributed, service-oriented environment utilizing RESTful services, and rich-client applications.
&lt;/p&gt;

&lt;p&gt;
	Alex is also involved in a number of Open Source projects like 
	&lt;a href="http://bistroframework.org/"&gt;Bistro&lt;/a&gt; and &lt;a href="http://ndjango.org/"&gt;NDjango&lt;/a&gt;, 
	and the .net side of CouchDB via &lt;a href="http://github.com/kolosy/Divan"&gt;Divan&lt;/a&gt; and 
	&lt;a href="http://github.com/kolosy/LoveSeat"&gt;LoveSeat&lt;/a&gt;
&lt;/p&gt;


&lt;p&gt;&lt;a href="http://altnetchicago-spblog.eventbrite.com"&gt;&lt;img src="http://www.eventbrite.com/static/images/button_ext/attend_this_event.gif" border="0" alt="" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=51931" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/.NET/default.aspx">.NET</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Tools/default.aspx">Tools</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/alt.net/default.aspx">alt.net</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Announcement/default.aspx">Announcement</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Community/default.aspx">Community</category></item><item><title>JavaScript and its love for zeroes</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/09/19/javascript-and-its-love-for-zeroes.aspx</link><pubDate>Sat, 19 Sep 2009 13:54:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:51520</guid><dc:creator>sergiopereira</dc:creator><slash:comments>6</slash:comments><description>&lt;div class="note"&gt;
	This post is part of a series called &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript-Demystified/default.aspx"&gt;
	JavaScript Demystified&lt;/a&gt;.
&lt;/div&gt;

&lt;p&gt;Answer quick. Do you know what date is being created here?&lt;/p&gt;
&lt;pre name="code" class="js:nogutter"&gt;var year = &amp;#39;2009&amp;#39;, month = &amp;#39;09&amp;#39;, day = &amp;#39;01&amp;#39;;
var date = new Date( 
             parseInt(year),
			 parseInt(month),
			 parseInt(day)
			 );	&lt;/pre&gt;

&lt;p&gt;
At first glance, it wouldn&amp;#39;t surprising that someone guesseed &lt;i&gt;September 1&lt;sup&gt;st&lt;/sup&gt; 2009&lt;/i&gt;.
However, I&amp;#39;d not be writing this post if that was the correct answer, right?
&lt;/p&gt;
&lt;p&gt;
There&amp;#39;s an interesting and tricky thing with the JavaScript &lt;code&gt;parseInt&lt;/code&gt; function: it
can parse strings with a numeric value in the decimal radix, but also in other radices. See the
following examples.
&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;//passing the radix explicitly
parseInt(&amp;#39;1011&amp;#39;, 10); // ==&amp;gt; 1011
parseInt(&amp;#39;1011&amp;#39;,  2); // ==&amp;gt; 11
parseInt(&amp;#39;1011&amp;#39;,  8); // ==&amp;gt; 521
parseInt(&amp;#39;1011&amp;#39;, 16); // ==&amp;gt; 4113
&lt;/pre&gt;

&lt;p&gt;Maybe you thought that if you didn&amp;#39;t pass the radix, then it would default to 10 because
it&amp;#39;s the obvious behavior. Well, no. In JavaScript the default behavior is to try to
identify one of the literal formats and interpret that. So here&amp;#39;s that in action:&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;//leaving JavaScript on its own
parseInt(&amp;#39;1011&amp;#39;); // ==&amp;gt; 1011 (decimal literal)
parseInt(&amp;#39;0x12&amp;#39;); // ==&amp;gt; 18   (hexadecimal literal)
parseInt(&amp;#39;0511&amp;#39;); // ==&amp;gt; 329  (octal literal)
parseInt(&amp;#39;0182&amp;#39;); // ==&amp;gt; 1    (whaaaa?!?!)
&lt;/pre&gt;

&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.09/js_2D00_newyear.png" align="left" alt="" /&gt;

&lt;p&gt;
If you are familiar with the literal notation for integer numbers in JavaScript,
and after I explained the default behavior of &lt;code&gt;parseInt&lt;/code&gt;, then
you probaly understood the results shown above. Well, maybe the last one deserves 
some comments.
&lt;/p&gt;
&lt;p&gt;
When JavaScript is parsing the string, if it finds a digit (number or alpha) that is invalid
in the chosen radix, it stops right there and parses only the portion of the string that
comes before that digit. So, since we started &lt;code&gt;&amp;#39;0182&amp;#39;&lt;/code&gt; with a leading zero, the 
octal radix is assumed. Then, because &lt;b&gt;8&lt;/b&gt; is not a valid octal digit, only &lt;code&gt;&amp;#39;01&amp;#39;&lt;/code&gt;
will be parsed, which becomes &lt;b&gt;1&lt;/b&gt;.
&lt;/p&gt;

&lt;div class="note"&gt;&lt;span class="legend"&gt;Tip #1:&lt;/span&gt;
If there&amp;#39;s any chance the string value you plan to parse into an integer number has
a leading zero (or a less likely &lt;b&gt;0x&lt;/b&gt;,) then be safe and pass the radix parameter
to your &lt;code&gt;parseInt&lt;/code&gt; call. If you&amp;#39;re extra paranoid, then always pass the radix.
&lt;/div&gt;


&lt;h3&gt;Back to our original question&lt;/h3&gt;

&lt;p&gt;Armed with the clarification made above, we can expand our example like this:&lt;/p&gt;
&lt;pre name="code" class="js:nogutter"&gt;//given:
var year = &amp;#39;2009&amp;#39;, month = &amp;#39;09&amp;#39;, day = &amp;#39;01&amp;#39;;
// then the following statement:
var date = new Date( 
         parseInt(year),
         parseInt(month),
         parseInt(day)
         );	
//...is equivalent to:
var date = new Date( 
         2009,
         0,  // ===&amp;gt; oopsie
         1
         );	&lt;/pre&gt;

&lt;p&gt;Hmmm, a zero in the month parameter. Will we have an error here? No, here comes the second potential surprise of this post.&lt;/p&gt;

&lt;div class="note"&gt;&lt;span class="legend"&gt;Tip #2:&lt;/span&gt;
When creating a new date using &lt;code&gt;new Date(year, month, day)&lt;/code&gt;, the &lt;code&gt;month&lt;/code&gt;
parameter, and &lt;b&gt;only&lt;/b&gt; the month parameter is zero-based (0 to 11).
&lt;/div&gt;

&lt;p&gt;So, in case the tips and the picture in this text were not enough to help you guessing the
date being created, here goes another completely gratuitous one with the answer.

&lt;p&gt;&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.09/js_2D00_newyear2.png" alt="" /&gt;&lt;/p&gt;
&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=51520" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Development/default.aspx">Development</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Tips-and-Tricks/default.aspx">Tips-and-Tricks</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript-Demystified/default.aspx">JavaScript-Demystified</category></item><item><title>Mozilla Add-Ons in Chicago</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/09/17/mozilla-add-ons-in-chicago.aspx</link><pubDate>Thu, 17 Sep 2009 17:38:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:51459</guid><dc:creator>sergiopereira</dc:creator><slash:comments>0</slash:comments><description>&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.09/addon.png" align="right" alt="" /&gt;
&lt;p&gt;
Later this month I&amp;#39;ll be attending the &lt;a href="https://wiki.mozilla.org/AddonMeetups:2009:Chicago"&gt;Mozilla Add-Ons Meetup&lt;/a&gt; in Chicago.
&lt;/p&gt;
&lt;p&gt;
I&amp;#39;m continually impressed with the extensibility of Mozilla applications and the amazing things people are doing with it. I&amp;#39;m interested in both the extensibility model and in writing a few custom extensions myself, even if it&amp;#39;s just for my own use. Given that it&amp;#39;s mostly XML and JavaScript, it should be right up my alley.
&lt;/p&gt;
&lt;p&gt;
After seeing &lt;a href="http://chicagocodecamp.com/Sessions.html#Firefox_Extensions"&gt;a presentation about building Firefox extensions&lt;/a&gt; earlier this year I decided I had to look into that more seriously.
&lt;/p&gt;
&lt;p&gt;
So if you&amp;#39;re in the area and wants to see what this is all about, this meetup might be a good way to get some info to get going.
&lt;/p&gt;
&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=51459" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Automation/default.aspx">Automation</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Announcement/default.aspx">Announcement</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Community/default.aspx">Community</category></item><item><title>ASP.NET MVC with jQuery SuperLoad</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/08/23/asp-net-mvc-with-jquery-superload.aspx</link><pubDate>Sun, 23 Aug 2009 10:59:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:50304</guid><dc:creator>sergiopereira</dc:creator><slash:comments>8</slash:comments><description>The other day &lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/2009/08/21/jquery-superload.aspx"&gt;I wrote 
about the jQuery SuperLoad plugin&lt;/a&gt; but
I couldn&amp;#39;t offer any real working sample of an application using it.

Today I&amp;#39;m here to rectify that and talk about the new sample code I&amp;#39;ve
recently added to &lt;a href="http://github.com/sergiopereira/SuperLoad"&gt;the project repository&lt;/a&gt;.


&lt;h3&gt;Adding products to your shopping cart&lt;/h3&gt;

The application has a single page, which lists a few books that you can add to your shopping cart. 
The cart is initially empty and when we add items to it, both the cart item list and the total price
(at the top of the page) get updated from a single Ajax call.

&lt;p&gt;&lt;a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.08/sample_2D00_mvc.png"&gt;&lt;img src="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.08/sample_2D00_mvc_2D00_small.png" alt="" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;The client side&lt;/h3&gt;

Here&amp;#39;s sample of what each of the products&amp;#39; HTML looks like. They each
are inside a &lt;code&gt;div&lt;/code&gt; which&amp;#39;s id contains the product&amp;#39;s id.

&lt;pre name="code" class="xml:nogutter"&gt;&amp;lt;div id=&amp;quot;product_8&amp;quot; class=&amp;quot;product&amp;quot;&amp;gt;
	&amp;lt;img src=&amp;quot;../../Content/images/prod_8.jpg&amp;quot; align=&amp;quot;left&amp;quot; /&amp;gt;

	&amp;lt;div class=&amp;quot;title&amp;quot;&amp;gt;Product 8&amp;lt;/div&amp;gt;
	&amp;lt;div class=&amp;quot;prodPrice&amp;quot; &amp;gt;$8.88&amp;lt;/div&amp;gt;
	Qty: &amp;lt;input type=&amp;quot;text&amp;quot; size=&amp;quot;2&amp;quot;  maxlength=&amp;quot;3&amp;quot; 
				class=&amp;quot;quantity&amp;quot; value=&amp;quot;1&amp;quot;/&amp;gt;
	&amp;lt;input type=&amp;quot;button&amp;quot; value=&amp;quot;Add to cart&amp;quot; class=&amp;quot;addButton&amp;quot; /&amp;gt;
&amp;lt;/div&amp;gt;&lt;/pre&gt;

We just need to fire one Ajax call whenever one of those &amp;quot;Add to cart&amp;quot; buttons is clicked.
Here&amp;#39;s the code that does that.

&lt;pre name="code" class="js:nogutter"&gt;$(&amp;#39;.addButton&amp;#39;).click(function() {
	var prod = $(this).parent(&amp;#39;.product&amp;#39;);
	var prodId = prod.attr(&amp;#39;id&amp;#39;).split(&amp;#39;_&amp;#39;)[1];
	var qty = prod.find(&amp;#39;.quantity&amp;#39;).val();

	$.superLoad({
		url: &amp;#39;/Shopping/AddItem&amp;#39;,
		type: &amp;#39;POST&amp;#39;,
		data: { product: prodId, quantity: qty },
		success: function() { $(&amp;#39;#empty&amp;#39;).remove(); }
	});
	
});&lt;/pre&gt;

As you can see, we are making a &lt;code&gt;superLoad()&lt;/code&gt; call to the &lt;code&gt;AddItem&lt;/code&gt; action in the 
&lt;code&gt;ShoppingController&lt;/code&gt;. Since this is a data modification call, we chose to use an HTTP &lt;b&gt;POST&lt;/b&gt; 
request. The posted data goes in the &lt;code&gt;data&lt;/code&gt; option. To tidy up things, we delete the &lt;i&gt;empty&lt;/i&gt; text from the cart 
(if it&amp;#39;s still there) once the call completes successfully.


&lt;h3&gt;Multiple results from a single action&lt;/h3&gt;	

The challenge on the server side is to come up with a 
&lt;a href="http://www.blogcoward.com/archive/2009/08/19/Maybe-we-should-talk-about-Sustainability-insteadAgain.aspx"&gt;sustainable&lt;/a&gt;
method of reusing existing actions and combine them in a single action result, formatted to SuperLoad&amp;#39;s liking and
returned to the browser.

To address that issue the sample comes with an implementation of a composite action result class specifically built for
the response format we are trying to create. That class is the &lt;code&gt;SuperLoadResult&lt;/code&gt;, listed below.

&lt;pre name="code" class="csharp:nogutter"&gt;public class SuperLoadResult : ActionResult
{
	public IEnumerable&amp;lt;SuperLoadAjaxContent&amp;gt; ContentItems { get; private set; }

	public SuperLoadResult(params SuperLoadAjaxContent[] contentItems)
	{
		ContentItems = new List&amp;lt;SuperLoadAjaxContent&amp;gt;();
		((List&amp;lt;SuperLoadAjaxContent&amp;gt;)ContentItems).AddRange(contentItems);
	}

	public override void ExecuteResult(ControllerContext context)
	{
		context.HttpContext.Response.ContentType = MediaTypeNames.Text.Html;

		context.HttpContext.Response.Write(&amp;quot;&amp;lt;div class=\&amp;quot;ajax-response\&amp;quot;&amp;gt;&amp;quot;);
		foreach (var item in ContentItems)
		{
			context.HttpContext.Response.Write(
				string.Format(&amp;quot;&amp;lt;div class=\&amp;quot;ajax-content\&amp;quot; title=\&amp;quot;{0} {1}\&amp;quot;&amp;gt;&amp;quot;,
			                  item.Command.CommandText, item.Selector));
			item.GetResult().ExecuteResult(context);
			context.HttpContext.Response.Write(&amp;quot;&amp;lt;/div&amp;gt;&amp;quot;);
		}
		context.HttpContext.Response.Write( &amp;quot;&amp;lt;/div&amp;gt;&amp;quot;);
	}
}&lt;/pre&gt;

I bet things will become clearer once I show it being used from the &lt;code&gt;AddItem&lt;/code&gt; action. So here it goes.

&lt;pre name="code" class="csharp:nogutter"&gt;[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddItem(int product, int quantity)
{
	var sku = GetProduct(product);
	var item = new CartItem(sku, quantity);
	var cart = GetCurrentCart();
	cart.Items.Add(item);

	//add all the separate action results that we want into 
	// a SuperLoad result, mapping each one to the right 
	// selector and update type.
	return new SuperLoadResult(
		new SuperLoadAjaxContent(&amp;quot;#cartTotal&amp;quot;, 
		                  SuperLoadCommand.Update, 
						  () =&amp;gt; CartTotal(cart)),

		new SuperLoadAjaxContent(&amp;quot;#cart&amp;quot;, 
		                  SuperLoadCommand.Append, 
						  () =&amp;gt; CartItem(item))
		);
}&lt;/pre&gt;

That last parameter to the &lt;code&gt;SuperLoadAjaxContent&lt;/code&gt;&amp;#39;s constructor is what will be invoked
to provide an &lt;code&gt;ActionResult&lt;/code&gt;-derived object, which will be executed and injected in the
right place of the combined response. If I needed to update more elements, I could simply pass
more instances of &lt;code&gt;SuperLoadAjaxContent&lt;/code&gt; to my &lt;code&gt;SuperLoadResult&lt;/code&gt;.

Both &lt;code&gt;CartTotal&lt;/code&gt; and &lt;code&gt;CartItem&lt;/code&gt; are regular action methods that
return a partial view from an .ascx template. Here&amp;#39;s how simple the &lt;code&gt;CartItem&lt;/code&gt; 
action is.

&lt;pre name="code" class="csharp:nogutter"&gt;public ActionResult CartItem(CartItem item)
{
	return PartialView(&amp;quot;CartItem&amp;quot;, item);
}&lt;/pre&gt;

Again, the entire sample is available for browsing, forking, or downloading at the 
&lt;a href="http://github.com/sergiopereira/SuperLoad"&gt;repository page&lt;/a&gt;.
&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=50304" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/.NET/default.aspx">.NET</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/SuperLoad/default.aspx">SuperLoad</category></item><item><title>jQuery SuperLoad</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/08/21/jquery-superload.aspx</link><pubDate>Fri, 21 Aug 2009 23:59:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:50169</guid><dc:creator>sergiopereira</dc:creator><slash:comments>12</slash:comments><description>&lt;p&gt;An important part of working with jQuery is to create plugins to 
simplify repetitive tasks. I write jQuery plugins all the time for
internal consumption of my applications.&lt;/p&gt; 

&lt;p&gt;Most of them are not of enough general purpose to be shared publicly.
Recently I created one that could stand on its own and I chose to 
make it available if anyone is interested.&lt;/p&gt;

&lt;h3&gt;Multiple Element Ajax Updates&lt;/h3&gt;

&lt;p&gt;&lt;a href="http://plugins.jquery.com/project/superload"&gt;jQuery SuperLoad&lt;/a&gt;
came out of the necessity to update more than one element in a page
without needing to do everything with JavaScript (and 
&lt;a href="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx"&gt;you know&lt;/a&gt; 
I&amp;#39;m not the one that avoids JavaScript).&lt;/p&gt;

&lt;p&gt;All of the page elements I needed to update with Ajax came from
page segments (partials, user controls, etc) that I had available on
my server side. It seemed appropriate to go back to the server to 
get updated versions of that same HTML. But I didn&amp;#39;t want to issue a 
separate &lt;code&gt;$.ajax()&lt;/code&gt; or &lt;code&gt;$(elem).load&lt;/code&gt; for each one of them. &lt;/p&gt;

&lt;p&gt;Using SuperLoad I can now return something like the following from
my server application and have more than one element updated.&lt;/p&gt;

&lt;pre name="code" class="xml:nogutter"&gt;&amp;lt;div class=&amp;quot;ajax-content&amp;quot;&amp;gt;
	&amp;lt;div title=&amp;quot;!appendTo #content .shoppingList&amp;quot;&amp;gt;
		&amp;lt;li&amp;gt;
			&amp;lt;img src=&amp;quot;/images/prod12345.png&amp;quot; class=&amp;quot;product-image&amp;quot;&amp;gt;
			&amp;lt;div class=&amp;quot;prodSummary&amp;quot;&amp;gt;
				&amp;lt;div class=&amp;quot;prodTitle&amp;quot;&amp;gt;ACME Product&amp;lt;/div&amp;gt;
				&amp;lt;div class=&amp;quot;prodPrice&amp;quot;&amp;gt;$12.34&amp;lt;/div&amp;gt;
			&amp;lt;/div&amp;gt;
		&amp;lt;/li&amp;gt;
	&amp;lt;/div&amp;gt;
	&amp;lt;div title=&amp;quot;!update #orderTotal&amp;quot;&amp;gt;
		Total: &amp;lt;span class=&amp;quot;totalPrice&amp;quot;&amp;gt;$47.22&amp;lt;/span&amp;gt;
		&amp;lt;div class=&amp;quot;specialOffer&amp;quot;&amp;gt;Eligible for free shipping!&amp;lt;/div&amp;gt;
	&amp;lt;/div&amp;gt;
	&amp;lt;script&amp;gt;
		$(&amp;#39;#orderTotal specialOffer&amp;#39;).effect(&amp;#39;highlight&amp;#39;);
	&amp;lt;/script&amp;gt;
&amp;lt;/div&amp;gt;&lt;/pre&gt;

&lt;p&gt;All that is needed for this to be correctly applied to the right
elements (selected by &lt;code&gt;&amp;quot;#content .shoppingList&amp;quot;&lt;/code&gt; and &lt;code&gt;&amp;quot;#orderTotal&amp;quot;&lt;/code&gt;
is a line of code similar to this example.&lt;/p&gt;

&lt;pre name="code" class="js:nogutter"&gt;$.superLoad({ 
	url: &amp;#39;/shopping/addItem&amp;#39;, 
	type: &amp;#39;POST&amp;#39;, 
	data: {product: 12345} 
});&lt;/pre&gt;

&lt;p&gt;Check the plugin source code comments or the &lt;a href="http://github.com/sergiopereira/SuperLoad"&gt;github repository page&lt;/a&gt;
for more details.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=50169" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/SuperLoad/default.aspx">SuperLoad</category></item><item><title>Interview for the Thirsty Developer Podcast</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/07/29/interview-for-the-thirsty-developer-podcast.aspx</link><pubDate>Thu, 30 Jul 2009 03:29:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:49657</guid><dc:creator>sergiopereira</dc:creator><slash:comments>0</slash:comments><description>&lt;p&gt;It was my turn to be interviewed by &lt;a href="http://www.davebost.com/blog/"&gt;Dave&lt;/a&gt; and &lt;a href="http://larryclarkin.com/"&gt;Larry&lt;/a&gt; for
 &lt;a href="http://thirstydeveloper.com/"&gt;The Thirsty Developer&lt;/a&gt; podcast.&lt;/p&gt;

&lt;p&gt;We talked a lot about all things JavaScript, its status, how people learn it (or avoid it), etc. I hope it&amp;#39;s an entertaining interview&lt;/p&gt; 

&lt;p&gt;You can download the interview from &lt;a href="http://thirstydeveloper.com/2009/07/29/70SergioOnJavaScript.aspx"&gt;the podcast page&lt;/a&gt;&lt;/p&gt;
&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=49657" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Announcement/default.aspx">Announcement</category></item><item><title>Video: WI-INETA JavaScript presentation</title><link>http://devlicio.us/blogs/sergio_pereira/archive/2009/07/17/video-wi-ineta-javascript-presentation.aspx</link><pubDate>Fri, 17 Jul 2009 15:17:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:49423</guid><dc:creator>sergiopereira</dc:creator><slash:comments>4</slash:comments><description>&lt;p&gt;
	I finally got around to properly record and publish one of those JavaScript presentations that
	I have been doing at local users groups. The video and the slide deck are available below.
&lt;/p&gt;

&lt;h3&gt;The video&lt;/h3&gt;

&lt;object width="545" height="349" id="viddler_ff61b0d8"&gt;&lt;param name="movie" value="http://www.viddler.com/player/ff61b0d8/" /&gt;&lt;param name="allowScriptAccess" value="always" /&gt;&lt;param name="allowFullScreen" value="true" /&gt;&lt;embed src="http://www.viddler.com/player/ff61b0d8/" width="545" height="349" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" name="viddler_ff61b0d8"&gt;&lt;/embed&gt;&lt;/object&gt;

&lt;p&gt;&amp;nbsp;&lt;/p&gt;

&lt;h3&gt;And the slide deck.&lt;/h3&gt;

&lt;div style="width:425px;text-align:left;" id="__ss_1727900"&gt;
	
	&lt;object style="margin:0px;" width="425" height="355"&gt;
	&lt;param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=wi-ineta-js-090715205636-phpapp02&amp;amp;rel=0&amp;amp;stripped_title=javascript-beyond-the-curly-braces" /&gt;
		&lt;param name="allowFullScreen" value="true" /&gt;
		&lt;param name="allowScriptAccess" value="always" /&gt;
		&lt;embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=wi-ineta-js-090715205636-phpapp02&amp;amp;rel=0&amp;amp;stripped_title=javascript-beyond-the-curly-braces" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"&gt;
		&lt;/embed&gt;
	&lt;/object&gt;
&lt;/div&gt;
&lt;p&gt;
If you prefer, you can download the &lt;a href="http://devlicio.us/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/sergio_5F00_pereira.2009.07/wi_2D00_ineta_2D00_js.pdf"&gt;slide deck&lt;/a&gt;.
&lt;p&gt;
&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=49423" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/JavaScript/default.aspx">JavaScript</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Video/default.aspx">Video</category><category domain="http://devlicio.us/blogs/sergio_pereira/archive/tags/Community/default.aspx">Community</category></item></channel></rss>