<?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 : jQuery</title><link>http://devlicio.us/blogs/sergio_pereira/archive/tags/jQuery/default.aspx</link><description>Tags: jQuery</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP1 (Build: 31106.3070)</generator><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>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></channel></rss>