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

<channel>
	<title>James Padolsey&#187; JavaScript category &#8211; James Padolsey</title>
	<atom:link href="http://james.padolsey.com/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://james.padolsey.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Sun, 22 Jan 2012 17:04:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2</generator>
		<item>
		<title>Using proxies to mimic existential-operator behaviour</title>
		<link>http://james.padolsey.com/javascript/using-proxies-to-mimic-existential-operator-behaviour/</link>
		<comments>http://james.padolsey.com/javascript/using-proxies-to-mimic-existential-operator-behaviour/#comments</comments>
		<pubDate>Sun, 01 Jan 2012 20:00:56 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=1990</guid>
		<description><![CDATA[The <a href="http://wiki.ecmascript.org/doku.php?id=harmony:proxies">Proxies API</a> is a low-level catch-all thing that you can wrap around your objects to implement almost anything you want within the syntactic limitations of JavaScript. <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Proxy">Firefox supports it</a>, and so does the latest version of V8 <a href="http://erik.eae.net/archives/2011/12/31/00.00.01/">apparently</a>.

The existential operator (the accessor kind), if&#8230;]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://wiki.ecmascript.org/doku.php?id=harmony:proxies">Proxies API</a> is a low-level catch-all thing that you can wrap around your objects to implement almost anything you want within the syntactic limitations of JavaScript. <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Proxy">Firefox supports it</a>, and so does the latest version of V8 <a href="http://erik.eae.net/archives/2011/12/31/00.00.01/">apparently</a>.</p>

<p>The existential operator (the accessor kind), if it existed in JavaScript, would allow us attempted access of nested properties in JavaScript without ever getting a TypeError. Here&#8217;s what usually happens:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> obj <span class="sy0">=</span> <span class="br0">&#123;</span> foo<span class="sy0">:</span> <span class="nu0">123</span> <span class="br0">&#125;</span><span class="sy0">;</span>
&nbsp;
obj.<span class="me1">foo</span>.<span class="me1">bar</span>.<span class="me1">bob</span><span class="sy0">;</span> <span class="co1">// Throws TypeError (obj.foo.bar is undefined)</span></pre></div></div>




<p>CoffeeScript implements an existential operator that allows you to attempt access at a property without throwing errors. It will fail quietly by returning a harmless <code>undefined</code> value. In CoffeeScript, it looks like this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">obj<span class="sy0">?</span>.<span class="me1">foo</span><span class="sy0">?</span>.<span class="me1">bar</span><span class="sy0">?</span>.<span class="me1">bob</span> <span class="co1">// returns undefined</span></pre></div></div>




<p>We can&#8217;t emulate this entirely but we can make a decent alternative using the Proxies API. In this example we&#8217;re using the dollar sign to indicate a existential-property-accessor-operator:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">obj <span class="sy0">=</span> <span class="br0">&#123;</span><span class="br0">&#125;</span><span class="sy0">;</span>
obj.<span class="me1">foo</span>$bar$bob<span class="sy0">;</span> <span class="co1">// =&gt; undefined</span>
obj <span class="sy0">=</span> <span class="br0">&#123;</span> foo<span class="sy0">:</span> <span class="br0">&#123;</span> bar<span class="sy0">:</span> <span class="br0">&#123;</span> bob<span class="sy0">:</span> <span class="nu0">321</span> <span class="br0">&#125;</span> <span class="br0">&#125;</span> <span class="br0">&#125;</span><span class="sy0">;</span>
obj <span class="sy0">=</span> existentially<span class="br0">&#40;</span>obj<span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// wrap it in magic</span>
obj.<span class="me1">foo</span>$bar$bob<span class="sy0">;</span> <span class="co1">// =&gt; 321</span></pre></div></div>




<p>No, it&#8217;s not as cool and no, you probably shouldn&#8217;t use it in production. Yes, it&#8217;ll fail if <code>obj</code> doesn&#8217;t exist. Anyway, I thought it was pretty neat. Here&#8217;s how it&#8217;s done:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">function</span> existentially<span class="br0">&#40;</span>obj<span class="br0">&#41;</span> <span class="br0">&#123;</span>
&nbsp;
  <span class="kw1">if</span> <span class="br0">&#40;</span>obj <span class="sy0">==</span> <span class="kw2">null</span><span class="br0">&#41;</span> <span class="kw1">return</span> obj<span class="sy0">;</span>
&nbsp;
  <span class="kw2">var</span> proxy <span class="sy0">=</span> handlerMaker<span class="br0">&#40;</span>obj<span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
  proxy.<span class="me1">get</span> <span class="sy0">=</span> <span class="kw2">function</span><span class="br0">&#40;</span>_<span class="sy0">,</span> <span class="kw3">name</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw3">name</span> <span class="sy0">=</span> <span class="kw3">name</span>.<span class="me1">split</span><span class="br0">&#40;</span><span class="st0">'$'</span><span class="br0">&#41;</span><span class="sy0">;</span>
    <span class="kw2">var</span> found <span class="sy0">=</span> obj<span class="sy0">;</span>
    <span class="kw1">while</span> <span class="br0">&#40;</span>
      <span class="kw3">name</span><span class="br0">&#91;</span><span class="nu0">0</span><span class="br0">&#93;</span> <span class="sy0">&amp;&amp;</span>
      <span class="kw2">null</span> <span class="sy0">!=</span> <span class="br0">&#40;</span>found <span class="sy0">=</span> found<span class="br0">&#91;</span><span class="kw3">name</span>.<span class="me1">shift</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#93;</span><span class="br0">&#41;</span>
    <span class="br0">&#41;</span><span class="sy0">;</span>
    <span class="kw1">return</span> found<span class="sy0">;</span>
  <span class="br0">&#125;</span><span class="sy0">;</span>
&nbsp;
  proxy.<span class="me1">set</span> <span class="sy0">=</span> <span class="kw2">function</span><span class="br0">&#40;</span>_<span class="sy0">,</span> <span class="kw3">name</span><span class="sy0">,</span> val<span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw3">name</span> <span class="sy0">=</span> <span class="kw3">name</span>.<span class="me1">split</span><span class="br0">&#40;</span><span class="st0">'$'</span><span class="br0">&#41;</span><span class="sy0">;</span>
    <span class="kw2">var</span> found <span class="sy0">=</span> obj<span class="sy0">;</span>
    <span class="kw1">while</span> <span class="br0">&#40;</span>
      <span class="kw3">name</span><span class="br0">&#91;</span><span class="nu0">1</span><span class="br0">&#93;</span> <span class="sy0">&amp;&amp;</span>
      <span class="kw2">null</span> <span class="sy0">!=</span> <span class="br0">&#40;</span>found <span class="sy0">=</span> found<span class="br0">&#91;</span><span class="kw3">name</span>.<span class="me1">shift</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#93;</span><span class="br0">&#41;</span>
    <span class="br0">&#41;</span><span class="sy0">;</span>
    <span class="kw1">if</span> <span class="br0">&#40;</span>found<span class="br0">&#41;</span> <span class="br0">&#123;</span>
      found<span class="br0">&#91;</span><span class="kw3">name</span><span class="br0">&#93;</span> <span class="sy0">=</span> val<span class="sy0">;</span>
    <span class="br0">&#125;</span>
    <span class="kw1">return</span> <span class="kw2">true</span><span class="sy0">;</span>
  <span class="br0">&#125;</span><span class="sy0">;</span>
&nbsp;
  <span class="kw1">return</span> Proxy.<span class="me1">create</span><span class="br0">&#40;</span>proxy<span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
<span class="br0">&#125;</span>
&nbsp;
<span class="co1">// fyi</span>
<span class="co1">//   a == null</span>
<span class="co1">// is the same as</span>
<span class="co1">//   a === undefined || a === null</span></pre></div></div>




<p>The referenced <code>handlerMaker</code> simply defines all fundamental traps. You can grab it from <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Proxy#No-op_forwarding_proxy">the MDN Proxy API page</a>.</p>

<p>You&#8217;ll notice that we&#8217;re also defining a <code>get</code> trap, which enables stuff like:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> foo <span class="sy0">=</span> existentially<span class="br0">&#40;</span>document.<span class="me1">getElementById</span><span class="br0">&#40;</span><span class="st0">'foo'</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="kw1">if</span> <span class="br0">&#40;</span>foo<span class="br0">&#41;</span> <span class="br0">&#123;</span> <span class="co1">// yes, we still need the initial null check</span>
  foo.<span class="me1">firstChild</span>$style$display <span class="sy0">=</span> <span class="st0">'none'</span><span class="sy0">;</span>
    <span class="co1">// won't throw an error, even if `firstChild` doesn't exist</span>
<span class="br0">&#125;</span></pre></div></div>




<p>Okay, granted, the dollar sign doesn&#8217;t suit well and we&#8217;re just pandering to what&#8217;s allowed in JS, but it&#8217;s still a good illustration of what&#8217;s possible with the Proxies API. You might want to use another fake operator &#8212; possibly something that isn&#8217;t likely to be found as part of a property name itself&#8230; something like <code>_$_</code> would be okay, except that it&#8217;s ugly and, just like <code>$</code>, carries no semantic value whatsoever.</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/using-proxies-to-mimic-existential-operator-behaviour/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Rampant Callback Syndrome</title>
		<link>http://james.padolsey.com/javascript/rampant-callback-syndrome/</link>
		<comments>http://james.padolsey.com/javascript/rampant-callback-syndrome/#comments</comments>
		<pubDate>Sat, 19 Nov 2011 23:03:54 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[node]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=1951</guid>
		<description><![CDATA[One of the common critiques of <a href="http://nodejs.org/">node.js</a> is that its (events-based) asynchronous model requires a lot of nested callback functions and generally uglier flow control than a synchronous model would allow. An example:


<pre class="javascript" style="font-family:monospace;">fs.<span class="me1">readFile</span><span class="br0">&#40;</span>path.<span class="me1">join</span><span class="br0">&#40;</span>base<span class="sy0">,</span> <span class="st0">'config.json'</span><span class="br0">&#41;</span><span class="sy0">,</span> <span class="kw2">function</span><span class="br0">&#40;</span>err<span class="sy0">,</span> data<span class="br0">&#41;</span><span class="br0">&#123;</span>
    <span class="kw1">if</span> <span class="br0">&#40;</span>data<span class="br0">&#41;</span> <span class="br0">&#123;</span>
        data <span class="sy0">=</span> JSON.<span class="me1">parse</span><span class="br0">&#40;</span>data<span class="br0">&#41;</span><span class="sy0">;</span>
        data.<span class="me1">forEach</span><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span>path<span class="br0">&#41;</span><span class="br0">&#123;</span>
            fs.<span class="me1">readFile</span><span class="br0">&#40;</span>path<span class="sy0">,</span> <span class="kw2">function</span><span class="br0">&#40;</span>err<span class="sy0">,</span> data<span class="br0">&#41;</span><span class="br0">&#123;</span>
                <span class="kw1">if</span> <span class="br0">&#40;</span>err<span class="br0">&#41;</span> <span class="br0">&#123;</span>
                    log<span class="br0">&#40;</span>err<span class="br0">&#41;</span>
                <span class="br0">&#125;</span> <span class="kw1">else</span> <span class="br0">&#123;</span>
                    data <span class="sy0">=</span> JSON.<span class="me1">parse</span><span class="br0">&#40;</span>data<span class="br0">&#41;</span><span class="sy0">;</span>
                    <span class="kw1">if</span> <span class="br0">&#40;</span>data.<span class="me1">url</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
                        http.<span class="me1">get</span><span class="br0">&#40;</span>url.<span class="me1">parse</span><span class="br0">&#40;</span>data.<span class="me1">url</span><span class="br0">&#41;</span><span class="sy0">,</span> <span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span>
                            <span class="co1">// ...absurdum ad infinitum</span>
                        <span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span>
                    <span class="br0">&#125;</span>
                <span class="br0">&#125;</span>
            <span class="br0">&#125;</span><span class="br0">&#41;</span>
        <span class="br0">&#125;</span><span class="br0">&#41;</span>
    <span class="br0">&#125;</span>
<span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre>




This isn't a trait unique to node.js though. Much&#8230;]]></description>
			<content:encoded><![CDATA[<p>One of the common critiques of <a href="http://nodejs.org/">node.js</a> is that its (events-based) asynchronous model requires a lot of nested callback functions and generally uglier flow control than a synchronous model would allow. An example:</pre>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">fs.<span class="me1">readFile</span><span class="br0">&#40;</span>path.<span class="me1">join</span><span class="br0">&#40;</span>base<span class="sy0">,</span> <span class="st0">'config.json'</span><span class="br0">&#41;</span><span class="sy0">,</span> <span class="kw2">function</span><span class="br0">&#40;</span>err<span class="sy0">,</span> data<span class="br0">&#41;</span><span class="br0">&#123;</span>
    <span class="kw1">if</span> <span class="br0">&#40;</span>data<span class="br0">&#41;</span> <span class="br0">&#123;</span>
        data <span class="sy0">=</span> JSON.<span class="me1">parse</span><span class="br0">&#40;</span>data<span class="br0">&#41;</span><span class="sy0">;</span>
        data.<span class="me1">forEach</span><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span>path<span class="br0">&#41;</span><span class="br0">&#123;</span>
            fs.<span class="me1">readFile</span><span class="br0">&#40;</span>path<span class="sy0">,</span> <span class="kw2">function</span><span class="br0">&#40;</span>err<span class="sy0">,</span> data<span class="br0">&#41;</span><span class="br0">&#123;</span>
                <span class="kw1">if</span> <span class="br0">&#40;</span>err<span class="br0">&#41;</span> <span class="br0">&#123;</span>
                    log<span class="br0">&#40;</span>err<span class="br0">&#41;</span>
                <span class="br0">&#125;</span> <span class="kw1">else</span> <span class="br0">&#123;</span>
                    data <span class="sy0">=</span> JSON.<span class="me1">parse</span><span class="br0">&#40;</span>data<span class="br0">&#41;</span><span class="sy0">;</span>
                    <span class="kw1">if</span> <span class="br0">&#40;</span>data.<span class="me1">url</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
                        http.<span class="me1">get</span><span class="br0">&#40;</span>url.<span class="me1">parse</span><span class="br0">&#40;</span>data.<span class="me1">url</span><span class="br0">&#41;</span><span class="sy0">,</span> <span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span>
                            <span class="co1">// ...absurdum ad infinitum</span>
                        <span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span>
                    <span class="br0">&#125;</span>
                <span class="br0">&#125;</span>
            <span class="br0">&#125;</span><span class="br0">&#41;</span>
        <span class="br0">&#125;</span><span class="br0">&#41;</span>
    <span class="br0">&#125;</span>
<span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>This isn't a trait unique to node.js though. Much of JavaScript, since it is a language heavily bound to the client-side and therefore DOM and user-initiated events, is very liable to "Rampant Callback Syndrome".</p>

<h3>Rampant Callback Syndrome</h3>

<p>Rampant Callback Syndrome is a serious issue in the JavaScript arena and if left unchecked will continue to spread like a disease, poisoning our dreams with its ominous creep.</p>

<p>In all seriousness, it is rather annoying, and is definitely something that can be avoided with nothing more than a light dose of decent application design and thought.</p>

<p>One pattern that I've become fairly attached to is the simple premise of providing an API to begin with, and letting it appear to be a (<em>mostly</em>) synchronous interface, but behind the scenes throw around events to make it work properly.</p>

<p>Let's say, for example, that we want to expose a Model API, for interfacing with our database.</p>

<p>When the model is instantiated we go about opening the connection to the database:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">function</span> Model<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
&nbsp;
    <span class="co1">// (not shown) ... configuration stuff ...</span>
&nbsp;
    <span class="kw1">this</span>.<span class="me1">server</span> <span class="sy0">=</span> <span class="kw2">new</span> mongodb.<span class="me1">Server</span><span class="br0">&#40;</span>
        <span class="kw1">this</span>.<span class="me1">config</span>.<span class="me1">address</span><span class="sy0">,</span>
        <span class="kw1">this</span>.<span class="me1">config</span>.<span class="me1">port</span><span class="sy0">,</span>
        <span class="br0">&#123;</span><span class="br0">&#125;</span>
    <span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
    <span class="co1">// (not shown) ... error checking ...</span>
&nbsp;
    <span class="kw1">this</span>.<span class="me1">db</span> <span class="sy0">=</span> <span class="kw2">new</span> mongodb.<span class="me1">Db</span><span class="br0">&#40;</span><span class="kw1">this</span>.<span class="me1">config</span>.<span class="me1">dbName</span><span class="sy0">,</span> <span class="kw1">this</span>.<span class="me1">server</span><span class="sy0">,</span> <span class="br0">&#123;</span><span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
    <span class="kw1">this</span>.<span class="me1">db</span>.<span class="kw3">open</span><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span>error<span class="sy0">,</span> client<span class="br0">&#41;</span><span class="br0">&#123;</span>
&nbsp;
        <span class="kw1">if</span> <span class="br0">&#40;</span>error<span class="br0">&#41;</span> <span class="br0">&#123;</span>
            <span class="kw1">this</span>.<span class="me1">error</span><span class="br0">&#40;</span><span class="st0">'DB: '</span> <span class="sy0">+</span> <span class="kw1">this</span>.<span class="me1">config</span>.<span class="me1">db</span> <span class="sy0">+</span> <span class="st0">' error: '</span><span class="sy0">,</span> error<span class="br0">&#41;</span><span class="sy0">;</span>
            <span class="kw1">return</span><span class="sy0">;</span>
        <span class="br0">&#125;</span>
&nbsp;
        <span class="kw1">this</span>.<span class="me1">collection</span> <span class="sy0">=</span> <span class="kw2">new</span> mongodb.<span class="me1">Collection</span><span class="br0">&#40;</span>client<span class="sy0">,</span> <span class="kw1">this</span>.<span class="me1">config</span>.<span class="me1">dbCollection</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
        <span class="kw1">this</span>._isOpen <span class="sy0">=</span> <span class="kw2">true</span><span class="sy0">;</span>
        <span class="kw1">this</span>.<span class="me1">emit</span><span class="br0">&#40;</span><span class="st0">'open'</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
    <span class="br0">&#125;</span>.<span class="me1">bind</span><span class="br0">&#40;</span><span class="kw1">this</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
    <span class="co1">// (not shown) ... other stuff ...</span>
&nbsp;
<span class="br0">&#125;</span></pre></div></div>




<p>The problem is that our <code>new Model</code> call will return before the connection to the database is open. Fortunately, as you can see above, in the callback to the <code>db.open</code> method we are setting a flag, <code>_isOpen</code>, to <code>true</code>, and we're emitting the <code>open</code> event. This Model happens to implement the <code>events.EventEmitter</code> interface which means we can fire and trigger on our object.</p>

<p>So, let's look at our calling-code:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> myModel <span class="sy0">=</span> <span class="kw2">new</span> Model<span class="br0">&#40;</span><span class="br0">&#123;</span> <span class="co2">/* config */</span> <span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
myModel.<span class="me1">find</span><span class="br0">&#40;</span><span class="br0">&#123;</span> username<span class="sy0">:</span> <span class="st0">'James'</span> <span class="br0">&#125;</span><span class="sy0">,</span> <span class="kw2">function</span><span class="br0">&#40;</span>data<span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="co1">// I can live with a single nested function. </span>
<span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>This is great! The code above shows none of the callback nonsense we saw earlier<sup>[1]</sup> -- we've abstracted it away. One <em>big</em> problem though is the <code>find</code> method is going to be called before our database connection is open. But, thanks to the events interface, we can hold off until our <code>open</code> event fires:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">Model.<span class="me1">prototype</span>.<span class="me1">find</span> <span class="sy0">=</span> <span class="kw2">function</span><span class="br0">&#40;</span>selector<span class="sy0">,</span> cb<span class="br0">&#41;</span><span class="br0">&#123;</span>
&nbsp;
    <span class="kw1">if</span> <span class="br0">&#40;</span><span class="kw1">this</span>._isOpen<span class="br0">&#41;</span> <span class="br0">&#123;</span>
&nbsp;
        <span class="co1">// If we're already open, let's go:</span>
&nbsp;
        <span class="kw1">this</span>.<span class="me1">collection</span>.<span class="me1">find</span><span class="br0">&#40;</span>selector<span class="br0">&#41;</span>.<span class="me1">toArray</span><span class="br0">&#40;</span>cb<span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
    <span class="br0">&#125;</span> <span class="kw1">else</span> <span class="br0">&#123;</span>
&nbsp;
        <span class="co1">// Otherwise, wait:</span>
&nbsp;
        <span class="kw2">var</span> args <span class="sy0">=</span> arguments<span class="sy0">;</span>
        <span class="kw1">this</span>.<span class="me1">on</span><span class="br0">&#40;</span><span class="st0">'open'</span><span class="sy0">,</span> <span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span>
            <span class="kw1">this</span>.<span class="me1">find</span>.<span class="me1">apply</span><span class="br0">&#40;</span><span class="kw1">this</span><span class="sy0">,</span> args<span class="br0">&#41;</span><span class="sy0">;</span>
            <span class="co1">// (added stability would be remove the event listener here)</span>
        <span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
    <span class="br0">&#125;</span>
&nbsp;
<span class="br0">&#125;</span><span class="sy0">;</span></pre></div></div>




<p>In the <code>else</code> block we register a new event listener, to listen for the <code>open</code> event, and when it fires, we're simply going to call the very same method (<code>find</code>) with the very same arguments. Obviously this is only possible if we're using callbacks (one of the arguments to <code>find()</code>). Obliterating all callbacks is not we're looking for; we're simply looking to minimise.</p>

<h3>Abstraction is the key</h3>

<p>We can cure 90% of Rampant Callback Syndrome by simply abstracting our code.</p>

<p>The great thing about the solution shown in this post is that you're able to provide the promised API immediately following instantiation -- you're not forcing the higher level of abstraction to fuss with what is a lower concern.</p>

<p><sup>[1]</sup><small>: Yes, I know they're doing completely different things. My point still stands.</small></p>
]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/rampant-callback-syndrome/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>JSAPI.info</title>
		<link>http://james.padolsey.com/javascript/jsapi-info/</link>
		<comments>http://james.padolsey.com/javascript/jsapi-info/#comments</comments>
		<pubDate>Tue, 01 Nov 2011 15:30:41 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[Cool Stuff]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Dojo]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Mootools]]></category>
		<category><![CDATA[Underscore]]></category>
		<category><![CDATA[YUI]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=1944</guid>
		<description><![CDATA[A while ago I made the &#8220;<a href="http://james.padolsey.com/jquery/">jQuery source viewer</a>&#8220;. It allows you to explore jQuery&#8217;s source and has a hackable URL pattern so you can get at what you need (e.g. <a href="james.padolsey.com/jquery/append">/jquery/append</a>).

I had been thinking about making a version 2 for sometime, and about&#8230;]]></description>
			<content:encoded><![CDATA[<p>A while ago I made the &#8220;<a href="http://james.padolsey.com/jquery/">jQuery source viewer</a>&#8220;. It allows you to explore jQuery&#8217;s source and has a hackable URL pattern so you can get at what you need (e.g. <a href="james.padolsey.com/jquery/append">/jquery/append</a>).</p>

<p>I had been thinking about making a version 2 for sometime, and about two weeks ago I started work on <a href="http://jsapi.info">JSAPI.info</a>. It&#8217;s built using node.js, and is more flexible than version 1 in that it enables you to explore the source of whatever library you want (as long as it&#8217;s <a href="https://github.com/padolsey/jsapi-info/blob/master/app/libs.json">specified</a>), not just jQuery.</p>

<h3>Demos</h3>

<ul>
  <li>jQuery (e.g. <a href="http://jsapi.info/jquery/css">/jquery/css</a>)</li>
  <li>Mootools (e.g. <a href="http://jsapi.info/mootools/flatten">/mootools/Array.prototype.flatten</a>)</li>

  <li>Dojo (e.g. <a href="http://jsapi.info/dojo/1/Color">/dojo/1/Color</a>)</li>
  <li>Underscore (e.g. <a href="http://jsapi.info/_/every">/_/every</a>)</li>
  <li>YUI (e.g. <a href="http://jsapi.info/yui/3/namespace">/yui/3/namespace</a>)</li>
</ul>

<p>As I said, the URLs are &#8220;hackable&#8221;, so you can specify the method and version you want. Each page has a link to the documentation for that method (if found), and a list of related links (methods under the same namespace) on the left hand side.</p>

<h3>How does it work?</h3>

<blockquote><p>It works by loading the library you specify into an instance of <a href="https://github.com/tmpvar/jsdom">jsdom</a>, and then evaluating the method you specify (in fully qualified form, e.g. jQuery.fn.css) within that instance. It then matches the <code>toString()</code> representation of that function (thanks V8!) against the source of the library, thus determining its location. It&#8217;s all operating under node.js, running via a beautiful configuration of nginx (primed to microcache!) on a linode box somewhere in London.</p></blockquote>

<h3>Yet to add&#8230;</h3>

<p>I&#8217;ve yet to add the following features, and plan on doing so in the near future. The <a href="https://github.com/padolsey/jsapi-info">source is up on Github</a> if anyone wants to help!</p>

<ul>
  <li><del datetime="2011-11-02T18:38:45+00:00">Links within source code leading to other parts of the API.</del> (<strong><a href="https://github.com/padolsey/jsapi-info/commit/50d4e50f8e86d594e5a7150696f1a6fa19cc3f61">DONE</a></strong>) The <a href="http://james.padolsey.com/jquery/">jQuery source viewer</a> already does this.</li>
  <li>Thinking about adding beautify-js &#8212; this&#8217;ll change the format of the code though, so it won&#8217;t be consistent with the source code, and thus the line numbers won&#8217;t match up.</li>
  <li>I was experimenting with full documentation support so the documentation for a specific method could appear alongside the source code, but I&#8217;m not sure if it would be a sensible addition, especially considering that it can just link to the documentation instead.</li>
  <li>Any other features you can think of?</li>
</ul>

<h3>Why?</h3>

<p>Have you ever tried to find the source of the <code>jQuery.fn.height</code> method? <a href="http://code.jquery.com/jquery-1.6.4.js">Try it now</a>. It&#8217;s tricky.</p>

<p>If you&#8217;re anything like me, you&#8217;ll hit CTRL-F and type the most popular function/method declaration patterns, including <code>function height...</code>, <code>height = funct...</code>, <code>height: function...</code>. None of these work for <code>jQuery.fn.height</code> because it&#8217;s defined differently. It&#8217;s not easy to find.</p>

<p>I very often need to find the source behind a method I&#8217;m using and there aren&#8217;t many easy ways to do so, and that&#8217;s why I originally created the jQuery source viewer. <a href="http://jsapi.info/">JSAPI.info</a> is a move in the right direction since it supports multiple libraries and, finally, has it&#8217;s own domain!</p>

<p>Please test it out and <a href="https://github.com/padolsey/jsapi-info/issues">let me know</a> if you catch any bugs.</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/jsapi-info/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Terse JavaScript 101 &#8211; part 2</title>
		<link>http://james.padolsey.com/javascript/terse-javascript-101-part-2/</link>
		<comments>http://james.padolsey.com/javascript/terse-javascript-101-part-2/#comments</comments>
		<pubDate>Sat, 29 Oct 2011 11:05:57 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=1937</guid>
		<description><![CDATA[<a href="http://james.padolsey.com/javascript/terse-javascript-101-part-1/">Part one</a>, posted last week, explored a few different ways of de-cluttering your JavaScript, and, in the process, making it more readable.

Some developers don&#8217;t like the idea of using a language&#8217;s more idiosyncratic features because it does, potentially, make your code less readable in&#8230;]]></description>
			<content:encoded><![CDATA[<p><a href="http://james.padolsey.com/javascript/terse-javascript-101-part-1/">Part one</a>, posted last week, explored a few different ways of de-cluttering your JavaScript, and, in the process, making it more readable.</p>

<p>Some developers don&#8217;t like the idea of using a language&#8217;s more idiosyncratic features because it does, potentially, make your code less readable in the eyes of those who haven&#8217;t learned the language properly. I think it&#8217;s still up for debate. While you&#8217;re pondering that, part II awaits&#8230;</p>

<p>If you haven&#8217;t checked out the <a href="http://james.padolsey.com/javascript/truthy-falsey/">&#8220;Truthy &#038; Falsey&#8221; introduction</a> then please do so before continuing.</p>

<h3>Looping</h3>

<p>It&#8217;s something we barely think about but JavaScript&#8217;s expressive diversity allows us to invent new patterns for looping. First, there&#8217;s the standard:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">;</span> i <span class="sy0">&lt;</span> array.<span class="me1">length</span><span class="sy0">;</span> i<span class="sy0">++</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><span class="br0">&#125;</span></pre></div></div>




<p>This is conventional and will be known to developers coming from any language. There&#8217;s nothing inherently wrong with it. That said, for me, it&#8217;s not ideal.</p>

<p>The first improvement I usually make is to cache the <code>length</code> property of the array:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">,</span> l <span class="sy0">=</span> array.<span class="me1">length</span><span class="sy0">;</span> i <span class="sy0">&lt;</span> l<span class="sy0">;</span> i<span class="sy0">++</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><span class="br0">&#125;</span></pre></div></div>




<p>This doesn&#8217;t make it shorter, but it does make it more efficient, although marginally so&#8230;</p>

<p>Another change we can make is to combine the iteration expression (<code>i++</code>) and the conditional expression (<code>i &lt; l</code>), like so:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i <span class="sy0">=</span> <span class="sy0">-</span><span class="nu0">1</span><span class="sy0">,</span> l <span class="sy0">=</span> array.<span class="me1">length</span><span class="sy0">;</span> <span class="sy0">++</span>i <span class="sy0">&lt;</span> l<span class="sy0">;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><span class="br0">&#125;</span></pre></div></div>




<p>Notice that we&#8217;re starting with an index of <code>-1</code>, but won&#8217;t worry because before the loop&#8217;s body runs, the conditional expression is run, and in the above code, the conditional expression is iterating the index and testing it against the length all in one.</p>

<p>It&#8217;s important to note that the prefix increment/decrement operators (<code>++i</code>/<code>--i</code>) return the changed value, while the postfix increment/decrement operators (<code>i++</code>/<code>i--</code>) return the old value. To make this clearer:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> x <span class="sy0">=</span> <span class="nu0">5</span><span class="sy0">;</span>
<span class="kw3">alert</span><span class="br0">&#40;</span>x<span class="sy0">++</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// alerts 5 (old value)</span>
<span class="kw3">alert</span><span class="br0">&#40;</span>x<span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// alerts 6</span>
&nbsp;
<span class="kw2">var</span> y <span class="sy0">=</span> <span class="nu0">5</span><span class="sy0">;</span>
<span class="kw3">alert</span><span class="br0">&#40;</span><span class="sy0">++</span>y<span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// alerts 6 (new value)</span>
<span class="kw3">alert</span><span class="br0">&#40;</span>y<span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// alerts 6</span></pre></div></div>




<p>Another looping &#8220;pattern&#8221; in JavaScript is to assign and rely on what&#8217;s returned from that assignment for the conditional expression:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> elements <span class="sy0">=</span> document.<span class="me1">getElementsByTagName</span><span class="br0">&#40;</span><span class="st0">'a'</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
<span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i <span class="sy0">=</span> <span class="sy0">-</span><span class="nu0">1</span><span class="sy0">,</span> el<span class="sy0">;</span> el <span class="sy0">=</span> elements<span class="br0">&#91;</span><span class="sy0">++</span>i<span class="br0">&#93;</span><span class="sy0">;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
  el<span class="sy0">;</span> <span class="co1">// =&gt; a single element</span>
<span class="br0">&#125;</span></pre></div></div>




<p>Yesterday&#8217;s post on truthy &#038; falsey bears some relevance here. The expression <code>el=elements[++i]</code> will return the value of <code>elements[++i]</code>. If this value is falsey the loop will not continue. An element list is full of truthy values (objects). We don&#8217;t need to be worried about falsey values. Note that in this approach, you may be sacrificing performance for terseness.</p>

<p>In many situations, we do want to iterate over falsey values too, e.g.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> myArray <span class="sy0">=</span> <span class="br0">&#91;</span><span class="nu0">1</span><span class="sy0">,</span> <span class="nu0">2</span><span class="sy0">,</span> <span class="nu0">3</span><span class="sy0">,</span> <span class="kw2">null</span><span class="sy0">,</span> <span class="nu0">8</span><span class="sy0">,</span> <span class="nu0">54</span><span class="sy0">,</span> <span class="kw2">null</span><span class="sy0">,</span> <span class="nu0">0</span><span class="sy0">,</span> <span class="nu0">32</span><span class="br0">&#93;</span><span class="sy0">;</span></pre></div></div>




<p>With something like this it would be best to use the traditional <code>i&lt;length</code> conditional expression, but if you&#8217;re so inclined feel free to mix the conditional and iteration expressions together like shown further up (<code>++i&lt;l</code>).</p>

<p>If we were feeling a bit crazy, we could combine everything &#8212; iteration, conditional test, and assignment of indexed value &#8212; in a single expression:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> array <span class="sy0">=</span> <span class="br0">&#91;</span><span class="st0">'a'</span><span class="sy0">,</span><span class="st0">'b'</span><span class="sy0">,</span><span class="st0">'c'</span><span class="br0">&#93;</span><span class="sy0">;</span>
&nbsp;
<span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i <span class="sy0">=</span> <span class="sy0">-</span><span class="nu0">1</span><span class="sy0">,</span> l <span class="sy0">=</span> array.<span class="me1">length</span><span class="sy0">,</span> <span class="kw1">item</span><span class="sy0">;</span> <span class="kw1">item</span> <span class="sy0">=</span> array<span class="br0">&#91;</span><span class="sy0">++</span>i<span class="br0">&#93;</span><span class="sy0">,</span> i <span class="sy0">&lt;</span> l<span class="sy0">;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
  <span class="kw3">alert</span><span class="br0">&#40;</span><span class="kw1">item</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="br0">&#125;</span>
&nbsp;
<span class="co1">// alerts, a, b, c</span></pre></div></div>




<p>Here we used the useful comma operator which always returns its right-hand operand. In this example we used it to make sure that <code>i &lt; l</code> is what the condition expression returns. Before the comma we&#8217;re assigning the value at the iterated index within the array.</p>

<p>I don&#8217;t really suggest doing all of this in one line, and to be honest, there&#8217;s nothing wrong with conventional looping structures. What I am trying to put across is how much expressive diversity JavaScript provides.</p>

<h3>Assignments</h3>

<p>Assignments are expressions too, so you can slot them in wherever you want:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> a <span class="sy0">=</span> <span class="nu0">1</span><span class="sy0">;</span>
<span class="kw3">alert</span><span class="br0">&#40;</span>a <span class="sy0">=</span> <span class="nu0">2</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// alerts 2</span>
<span class="kw3">alert</span><span class="br0">&#40;</span>a<span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// alerts 2</span></pre></div></div>




<p>An assignment operator will always return whatever is on its right-hand side. Be careful with slotting in assignment expressions wherever you want though, because they can be misconstrued for equality operators. For example:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> match<span class="sy0">;</span>
&nbsp;
<span class="kw1">if</span> <span class="br0">&#40;</span>match <span class="sy0">=</span> <span class="st0">'1/2/3'</span>.<span class="me1">match</span><span class="br0">&#40;</span><span class="co2">/\d/</span><span class="br0">&#41;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
  <span class="co1">//...</span>
<span class="br0">&#125;</span></pre></div></div>




<p>To some, upon initial inspection, it may appear that we&#8217;re testing <code>match</code> for equality against <code>'1/2/3'.match(/\d/)</code> when in fact the latter is being assigned to the former, and the <code>if</code> statement will run if the assignment expression returns a truthy value (i.e. if its right-hand side operand is truthy).</p>

<h3>Casting to a number</h3>

<p>Quick and easy:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> str <span class="sy0">=</span> <span class="st0">'222'</span><span class="sy0">;</span>
<span class="kw2">var</span> num <span class="sy0">=</span> Number<span class="br0">&#40;</span>str<span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; 222</span>
&nbsp;
<span class="kw1">typeof</span> num<span class="sy0">;</span> <span class="co1">// =&gt; 'number'</span></pre></div></div>




<p>A shortcut is the unary plus (<code>+</code>) operator, used like so:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> str <span class="sy0">=</span> <span class="st0">'222'</span><span class="sy0">;</span>
<span class="kw2">var</span> num <span class="sy0">=</span> <span class="sy0">+</span>str<span class="sy0">;</span> <span class="co1">// =&gt; 222</span>
&nbsp;
<span class="kw1">typeof</span> num<span class="sy0">;</span> <span class="co1">// =&gt; 'number'</span></pre></div></div>




<p>It works in exactly the same way.</p>

<h3>Casting to a string</h3>

<p>Once again, quick and easy:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> arr <span class="sy0">=</span> <span class="br0">&#91;</span><span class="nu0">1</span><span class="sy0">,</span><span class="nu0">2</span><span class="sy0">,</span><span class="nu0">3</span><span class="br0">&#93;</span><span class="sy0">;</span>
<span class="kw2">var</span> str <span class="sy0">=</span> String<span class="br0">&#40;</span>arr<span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; '1,2,3'</span>
&nbsp;
<span class="kw1">typeof</span> str<span class="sy0">;</span> <span class="co1">// =&gt; 'string'</span></pre></div></div>




<p>The shortcut, this time, is to simply concatenate an empty string to the value that you&#8217;re casting:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> arr <span class="sy0">=</span> <span class="br0">&#91;</span><span class="nu0">1</span><span class="sy0">,</span><span class="nu0">2</span><span class="sy0">,</span><span class="nu0">3</span><span class="br0">&#93;</span><span class="sy0">;</span>
<span class="kw2">var</span> str <span class="sy0">=</span> <span class="st0">''</span> <span class="sy0">+</span> arr<span class="sy0">;</span> <span class="co1">// =&gt; '1,2,3'</span>
&nbsp;
<span class="kw1">typeof</span> str<span class="sy0">;</span> <span class="co1">// =&gt; 'string'</span></pre></div></div>




<h3>Saving references</h3>

<p>Property lookup can be verbose and inefficient. To save space and to benefit performance it&#8217;s common to save references and access those properties via the new reference instead of having to evaluate the entire expression every time you want the nested value:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="co1">// Original:</span>
document.<span class="me1">body</span>.<span class="me1">style</span>.<span class="me1">color</span><span class="sy0">;</span>
&nbsp;
<span class="co1">// &quot;Caching&quot;</span>
<span class="kw2">var</span> style <span class="sy0">=</span> document.<span class="me1">body</span>.<span class="me1">style</span><span class="sy0">;</span>
&nbsp;
<span class="co1">// Whenever I need to access the `color` value:</span>
style.<span class="me1">color</span><span class="sy0">;</span></pre></div></div>




<p>It&#8217;s often referred to as caching. Essentially, all that&#8217;s happening is that a new reference is being created for an object and being assigned to an identifier that you specify. Let&#8217;s start with this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> data <span class="sy0">=</span> <span class="br0">&#123;</span>
    config<span class="sy0">:</span> <span class="br0">&#123;</span>
        doSomething<span class="sy0">:</span> <span class="kw2">function</span><span class="br0">&#40;</span><span class="kw1">item</span><span class="br0">&#41;</span><span class="br0">&#123;</span>
            <span class="kw3">alert</span><span class="br0">&#40;</span><span class="kw1">item</span><span class="br0">&#41;</span><span class="sy0">;</span>
        <span class="br0">&#125;</span>
    <span class="br0">&#125;</span>
<span class="br0">&#125;</span><span class="sy0">;</span>
&nbsp;
<span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i <span class="sy0">=</span> <span class="sy0">-</span><span class="nu0">1</span><span class="sy0">,</span> l <span class="sy0">=</span> someArray.<span class="me1">length</span><span class="sy0">;</span> <span class="sy0">++</span>i <span class="sy0">&lt;</span> l<span class="sy0">;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    data.<span class="me1">config</span>.<span class="me1">doSomething</span><span class="br0">&#40;</span>someArray<span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<p>It would make sense to minimise the amount of property access that needs to occur within the loop, and thus, potentially, anywhere else in our application that references <code>data.config</code> too:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> config <span class="sy0">=</span> data.<span class="me1">config</span><span class="sy0">;</span></pre></div></div>




<p>Now the loop can simply reference <code>config</code> instead of <code>data.config</code>:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i <span class="sy0">=</span> <span class="sy0">-</span><span class="nu0">1</span><span class="sy0">,</span> l <span class="sy0">=</span> someArray.<span class="me1">length</span><span class="sy0">;</span> <span class="sy0">++</span>i <span class="sy0">&lt;</span> l<span class="sy0">;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    config.<span class="me1">doSomething</span><span class="br0">&#40;</span>someArray<span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<p>We could even &#8220;cache&#8221; the function itself:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> doSomething <span class="sy0">=</span> data.<span class="me1">config</span>.<span class="me1">doSomething</span><span class="sy0">;</span></pre></div></div>




<p>And then call it directly within the loop:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw2">var</span> i <span class="sy0">=</span> <span class="sy0">-</span><span class="nu0">1</span><span class="sy0">,</span> l <span class="sy0">=</span> someArray.<span class="me1">length</span><span class="sy0">;</span> <span class="sy0">++</span>i <span class="sy0">&lt;</span> l<span class="sy0">;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    doSomething<span class="br0">&#40;</span>someArray<span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<p><strong>IMPORTANT</strong>: It&#8217;s important to note that, when you assign a member function (that is, a function that is a property of an object) you are de-binding its <code>this</code> value, i.e. the context in which it runs. Here&#8217;s an example:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> obj <span class="sy0">=</span> <span class="br0">&#123;</span>
    value<span class="sy0">:</span> <span class="nu0">234</span><span class="sy0">,</span>
    fn<span class="sy0">:</span> <span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span> <span class="kw1">return</span> <span class="kw1">this</span>.<span class="me1">value</span><span class="sy0">;</span> <span class="br0">&#125;</span>
<span class="br0">&#125;</span><span class="sy0">;</span>
&nbsp;
obj.<span class="me1">fn</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; 234</span>
&nbsp;
<span class="kw2">var</span> fn <span class="sy0">=</span> obj.<span class="me1">fn</span><span class="sy0">;</span>
fn<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; undefined</span></pre></div></div>




<p>De-binding the <code>fn</code> method will make its context the global (window) object instead of the <code>obj</code> which we defined, so when our <code>fn</code> function looks for its `this.value` it won&#8217;t find it (because <code>this</code> is the <code>window</code>, which doesn&#8217;t have `value` defined).</p>

<h3>End of part 2</h3>

<p>Comment if you feel compelled.</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/terse-javascript-101-part-2/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Truthy &amp; Falsey</title>
		<link>http://james.padolsey.com/javascript/truthy-falsey/</link>
		<comments>http://james.padolsey.com/javascript/truthy-falsey/#comments</comments>
		<pubDate>Wed, 19 Oct 2011 21:36:33 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=1912</guid>
		<description><![CDATA[Before we continue with the &#8220;Terse JavaScript 101&#8243; series, we&#8217;re going to take a break and explore, in detail, <em>truthy</em> and <em>falsey</em>.

These are fundamental topics which I should have covered in more detail yesterday. There is copious information on this elsewhere online, so don&#8217;t feel&#8230;]]></description>
			<content:encoded><![CDATA[<p>Before we continue with the &#8220;Terse JavaScript 101&#8243; series, we&#8217;re going to take a break and explore, in detail, <em>truthy</em> and <em>falsey</em>.</p>

<p>These are fundamental topics which I should have covered in more detail yesterday. There is copious information on this elsewhere online, so don&#8217;t feel limited to this post in your study.</p>

<p>
<strong>Truthy</strong>: Something which evaluates to TRUE.<br/>
<strong>Falsey</strong>: Something which evaluates to FALSE.<br/>
</p>

<p>It&#8217;s mostly logical. One (1) is truthy, Zero (0) is falsey. An object of any kind (including functions, arrays, RegExp objects, etc.) is always truthy. The easiest way to determine if something is truthy is to determine that it&#8217;s <em>not</em> falsey. There are only five falsey values in JavaScript:</p>

<p><code>undefined</code>, <code>null</code>, <code>NaN</code>, <code>0</code>, <code>""</code> (<em>empty string</em>), and <code>false</code>, of course.</p>

<p><em><strong>Note</strong></em>: It is possible to explicitly wrap a primitive (string, number, null, undefined, boolean) in an object, which will make it truthy. For example, <code>0</code> (<em>zero</em>) is falsey, but <code>new Number(0)</code> is truthy. A scarier example is <code>new Boolean(false)</code> which is also truthy! Be careful. Only very rarely should you need to explicitly wrap primitives.</p>

<p>Why should you care what&#8217;s truthy and what&#8217;s falsey?</p>

<p>A value&#8217;s truthi&#8217;ness determines what it will evaluate to in logical expressions. For example:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">if</span> <span class="br0">&#40;</span><span class="nu0">0</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw3">alert</span><span class="br0">&#40;</span><span class="st0">'ALERT'</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<p>We know that the <code>alert()</code> call will never run, because <code>0</code>, being a falsey value, doesn&#8217;t satisfy the <code>if</code> statement&#8217;s condition &#8212; i.e. to run only if the passed expression is NOT falsey.</p>

<p><a href="http://bclary.com/2004/11/07/#a-12.5">From the spec</a>:</p>

<blockquote>
<p>The production IfStatement : if ( Expression ) Statement is evaluated as follows:</p>


<div class="wp_syntax"><div class="code"><pre class="txt" style="font-family:monospace;">1. Evaluate Expression.
2. Call GetValue(Result(1)).
&nbsp;
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
&nbsp;
3. Call ToBoolean(Result(2)).
&nbsp;
↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑
&nbsp;
4. If Result(3) is false, return (normal, empty, empty).
5. Evaluate Statement.
6. Return Result(5).</pre></div></div>



</blockquote>

<p><small>If you&#8217;re wondering, the phrase <em>return (normal, empty, empty)</em> essentially, means: continue with the program in a normal fashion. See <a href="http://bclary.com/2004/11/07/#a-8.9">8.9</a> for more.</small></p>

<p>As the subtle arrows point out, the bit we&#8217;re interested in is step 3, which calls ToBoolean with the result of step 2, which is essentially (<a href="http://bclary.com/2004/11/07/#a-8.7.1">*</a>) the value you passed in. But what is <em>ToBoolean</em>??</p>

<p><a href="http://bclary.com/2004/11/07/#a-9.2">ToBoolean</a> is simple:</p>

<table summary="Boolean Conversion">
<col width="150" />
<thead>
  <tr>
    <th>Input Type</th>

    <th>Result</th>
  </tr>
</thead>

<tbody>

  <tr>
    <td>Undefined</td>

    <td><b>false</b></td>
  </tr>

  <tr>
    <td>Null</td>

    <td><b>false</b></td>
  </tr>

  <tr>
    <td>Boolean</td>

    <td>The result equals the input argument (no conversion).</td>
  </tr>

  <tr>
    <td>Number</td>

    <td>The result is <b>false</b> if the argument is <b>+0,
    -0,</b> or NaN; otherwise the result is <b>true.</b></td>

  </tr>

  <tr>
    <td>String</td>

    <td>The result is <b>false</b> if the argument is the empty
    string (its length is zero); otherwise the result is
    <b>true.</b></td>
  </tr>

  <tr>
    <td>Object</td>

    <td><b>true</b></td>
  </tr>
</tbody>
</table>

<p>I hope this has made it clear enough.</p>

<h3>Enough of the spec!</h3>

<p>We now know what happens when we pass something as an <code>if</code> statement&#8217;s expression (<code>if(..this bit..){}</code>), but how much relevance does <em>truthy</em> and <em>falsey</em> have in other logical contexts? Well, a lot.</p>

<p>Let&#8217;s explore the basic <code>if</code> statement one last time though:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">if</span> <span class="br0">&#40;</span>X<span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="co1">// If this code runs, what have we proven about X?</span>
    <span class="kw3">alert</span><span class="br0">&#40;</span><span class="nu0">123</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<p>If <code>123</code> is alerted what can we say (for sure) about X? We can definitely say that it is NOT one of: <code>undefined</code>, <code>null</code>, <code>NaN</code>, <code>0</code>, <code>""</code> (<em>empty string</em>), or <code>false</code>. We can therefore say that <code>X</code> is truthy. It might be the literal value <code>true</code>, a number that&#8217;s not zero, an array, a function, etc.</p>

<p>Remember, everything in JavaScript that isn&#8217;t a primative value can be considered an object. Functions are objects. Arrays are objects. And all objects are truthy.</p>

<p>Since all objects are truthy, code like this is quite common:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> el <span class="sy0">=</span> document.<span class="me1">getElementById</span><span class="br0">&#40;</span><span class="st0">'foo'</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
<span class="kw1">if</span> <span class="br0">&#40;</span>el<span class="br0">&#41;</span> <span class="br0">&#123;</span>
    el.<span class="me1">style</span>.<span class="me1">color</span> <span class="sy0">=</span> <span class="st0">'red'</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<p><code>el</code> is not a boolean, it&#8217;s just an object (in this case, a DOM Element object). The if block only executes if its expression is truthy. We could be more explicit though. The <code>getElementById</code> function returns <code>null</code> if it doesn&#8217;t find the element, so we could do:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> el <span class="sy0">=</span> document.<span class="me1">getElementById</span><span class="br0">&#40;</span><span class="st0">'foo'</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
<span class="kw1">if</span> <span class="br0">&#40;</span>el <span class="sy0">!==</span> <span class="kw2">null</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    el.<span class="me1">style</span>.<span class="me1">color</span> <span class="sy0">=</span> <span class="st0">'red'</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<p>There&#8217;s usually little advantage in explicitly stating the falsey value that you&#8217;re looking for. Sometimes, you might want to guard against a <code>null</code> or an <code>undefined</code> but allow <code>false</code>, for example. In such circumstances, obviously, use the explicit syntax (strict equality and strict inequality operators &#8211; <code>===/!==</code>).</p>

<p>The <code>ToBoolean</code> thing that we referenced above happens in all logical contexts in JavaScript. For example, the <code>&#038;&#038;</code> (logical AND) operator:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="nu0">0</span> <span class="sy0">&amp;&amp;</span> <span class="kw3">alert</span><span class="br0">&#40;</span><span class="nu0">0</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="nu0">1</span> <span class="sy0">&amp;&amp;</span> <span class="kw3">alert</span><span class="br0">&#40;</span><span class="nu0">1</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>In this case, only <code>1</code> will be alerted, since zero is falsey and therefore does not satisfy the <code>&#038;&#038;</code>&#8216;s desire for a left-hand truthy operand. The logical AND operator will only evaluate its right-hand operand if its left-hand operand is truthy.</p>

<p>Further up we checked that the return value of <code>getElementById</code> wasn&#8217;t null by simply checking if it was truthy. If <code>el</code> was truthy then we knew the element existed in the DOM and we could begin to interact with it programatically.</p>

<p>We use a similar concept with object access.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw3">alert</span><span class="br0">&#40;</span>foo.<span class="me1">bar</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// Alerting the value of the 'bar' property of 'foo'</span></pre></div></div>




<p>The only values that will throw an error when you try to access a property are <code>null</code> and <code>undefined</code>. So, if <code>foo</code> is truthy then we can safely attempt to access it&#8217;s <code>bar</code> property without worrying about exceptions being thrown.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">if</span> <span class="br0">&#40;</span>foo<span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw3">alert</span><span class="br0">&#40;</span>foo.<span class="me1">bar</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<h3>Assume carefully</h3>

<p>With our if statement we have only proven that <code>foo</code> is truthy. It still might not be the object we expect. This is something to consider. Normally though, it&#8217;s safe enough to suppose that if some obscurely named value is not falsey, it&#8217;ll be the truthy value you desire and not something you don&#8217;t want.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">element.<span class="me1">addEventListener</span> <span class="sy0">?</span>
    element.<span class="me1">addEventListener</span><span class="br0">&#40;</span><span class="st0">'click'</span><span class="sy0">,</span> func<span class="sy0">,</span> <span class="kw2">false</span><span class="br0">&#41;</span> <span class="sy0">:</span>
    element.<span class="me1">attachEvent</span><span class="br0">&#40;</span><span class="st0">'onclick'</span><span class="sy0">,</span> func<span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>Here we make some assumptions:</p>

<ol>
    <li>If element has a property <code>addEventListener</code> and its value is something truthy, it must be a function, so we&#8217;ll call it.</li>
    <li>If it doesn&#8217;t exist then <code>attachEvent</code> must exist and must be a function.</li>
</ol>

<p>The code above happens to be working around old IE versions that don&#8217;t have the W3C DOM Event method, <code>addEventListener</code>. The assumptions I&#8217;m making are considered safe in the environments that I intend my web app to operate in, but they may not be safe assumptions in other environments, so it&#8217;s important to be wary of the fact that: just because something is truthy doesn&#8217;t mean it&#8217;s the truthy value you happen to be looking for (the same goes for falsi&#8217;ness).</p>

<p>It&#8217;s common to attempt deep object access using the following structure:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">a <span class="sy0">&amp;&amp;</span> a.<span class="me1">b</span> <span class="sy0">&amp;&amp;</span> a.<span class="me1">b</span>.<span class="me1">c</span> <span class="sy0">&amp;&amp;</span> a.<span class="me1">b</span>.<span class="me1">c</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<ol>
    <li>Make sure <code>a</code> is truthy.</li>
    <li>Make sure <code>a.b</code> is truthy (and thus exists).</li>
    <li>Make sure <code>a.b.c</code> is truthy (and thus exists).</li>
    <li>Call <code>a.b.c</code>.</li>
</ol>

<p>Again, we&#8217;re making assumptions, but we already knew that. This structure is very useful, although too much of it can make your code bloated, so maybe consider other options. For one: consider what you CAN safely assume. In some instances, you may be able to do this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">a <span class="sy0">&amp;&amp;</span> a.<span class="me1">b</span>.<span class="me1">c</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<ol>
    <li>Make sure <code>a</code> is truthy.</li>
    <li>Call <code>a.b.c</code>.</li>
</ol>

<p>In this example, we&#8217;ve determined that it is safe to assume that if <code>a</code> is truthy, it is the very object that we&#8217;re looking for, and therefore must have a minimum structure of: <code>a={b:{c:function(){...}}}</code>. We&#8217;re aware of our own data structure so can make this assumption.</p>

<h3>Explicit booleans</h3>

<p>You might be left wondering why we even bother having proper boolean values in JavaScript if we can get around quite easily with our other truthy and falsey values. And it&#8217;s true, we could manage without these booleans, and we rarely check for them explicitly. We usually just do something like:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">if</span> <span class="br0">&#40;</span>foo.<span class="me1">isAFoo</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="co1">// ...</span>
<span class="br0">&#125;</span></pre></div></div>




<p><code>foo.isAFoo()</code> could return any truthy value (not necessarily the boolean of <code>true</code>) and it would make no difference to the code execution.</p>

<p>But, it is important, in many situations, to be explicit in our intentions. So we should insist on using real booleans when there is a binary decision to make (two possible values).</p>

<p>To cast a value to its boolean representation, we can just use <code>ToBoolean</code>. We can indirectly use this internal method by calling the <code>Boolean</code> constructor as a function:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">Boolean<span class="br0">&#40;</span><span class="nu0">0</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span></pre></div></div>




<p>It will return a boolean value &#8212; either true or false, and is a really quick way of finding out whether a value is truthy of falsey:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">Boolean<span class="br0">&#40;</span>undefined<span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span>
Boolean<span class="br0">&#40;</span><span class="kw2">null</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span>
Boolean<span class="br0">&#40;</span><span class="kw2">false</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span>
Boolean<span class="br0">&#40;</span><span class="nu0">0</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span>
Boolean<span class="br0">&#40;</span><span class="st0">&quot;&quot;</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span>
Boolean<span class="br0">&#40;</span>NaN<span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span>
&nbsp;
Boolean<span class="br0">&#40;</span><span class="nu0">1</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; true</span>
Boolean<span class="br0">&#40;</span><span class="br0">&#91;</span><span class="nu0">1</span><span class="sy0">,</span><span class="nu0">2</span><span class="sy0">,</span><span class="nu0">3</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; true</span>
Boolean<span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span><span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// =&gt; true</span></pre></div></div>




<p>A well-known and widely used shortcut is to use the logical-NOT operator twice, like so:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="sy0">!!</span><span class="kw2">null</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span>
<span class="sy0">!!</span><span class="nu0">0</span><span class="sy0">;</span> <span class="co1">// =&gt; false</span>
<span class="sy0">!!</span><span class="nu0">123</span><span class="sy0">;</span> <span class="co1">// =&gt; true</span>
<span class="sy0">!!</span><span class="st0">'foo'</span><span class="sy0">;</span> <span class="co1">// =&gt; true</span></pre></div></div>




<p>I&#8217;ll leave that up to you to figure out <img src='http://james.padolsey.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>

<h3>[complete!]</h3>

<p>That&#8217;s it for today. Hopefully this has served as, at least, a minimal introduction to truthy &#038; falsey.</p>
]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/truthy-falsey/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Terse JavaScript 101 &#8211; part 1</title>
		<link>http://james.padolsey.com/javascript/terse-javascript-101-part-1/</link>
		<comments>http://james.padolsey.com/javascript/terse-javascript-101-part-1/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 21:23:00 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Expressions]]></category>
		<category><![CDATA[Readability]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=1896</guid>
		<description><![CDATA[While some folk will argue that verbose code aids readability, I think almost the opposite, and in this post I&#8217;m going to list some basic tips for minimising redundant clutter in your code. JavaScript is a fun language at its core &#8212; it&#8217;s worth learning&#8230;]]></description>
			<content:encoded><![CDATA[<p>While some folk will argue that verbose code aids readability, I think almost the opposite, and in this post I&#8217;m going to list some basic tips for minimising redundant clutter in your code. JavaScript is a fun language at its core &#8212; it&#8217;s worth learning the tiny details.</p>

<p>I hope this post is useful to someone. I wrote it <strong>not</strong> for beginners (although it will be helpful to them), but for all those people writing JavaScript on a daily basis yet haven&#8217;t been afforded the time/motivation to get to know the language properly.</p>

<h3>new Object()</h3>

<p>Nope, don&#8217;t do this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> o <span class="sy0">=</span> <span class="kw2">new</span> Object<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>Or any of this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> a <span class="sy0">=</span> <span class="kw2">new</span> Array<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="kw2">var</span> b <span class="sy0">=</span> <span class="kw2">new</span> Object<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span>
<span class="kw2">var</span> c <span class="sy0">=</span> <span class="kw2">new</span> RegExp<span class="br0">&#40;</span><span class="st0">&quot;1(.)3&quot;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>Do this instead:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> a <span class="sy0">=</span> <span class="br0">&#91;</span><span class="br0">&#93;</span><span class="sy0">;</span>
<span class="kw2">var</span> b <span class="sy0">=</span> <span class="br0">&#123;</span><span class="br0">&#125;</span><span class="sy0">;</span>
<span class="kw2">var</span> c <span class="sy0">=</span> <span class="co2">/1(.)3/</span><span class="sy0">;</span></pre></div></div>




<p>Array literal, object literal, regular expression literal. They rock. There&#8217;s usually no need to use the constructor functions when literals are available (please see the note below though).</p>

<p><em>Note</em>: There are situations when calling <code>Array</code> or <code>RegExp</code> directly can be useful. In such situations, you needn&#8217;t bother with the <code>new</code> operator. <code>Array(1,2,3)</code> will produce the same as <code>new Array(1,2,3)</code>. Calling <code>RegExp</code> directly can be useful for dynamically building a regular expression from various strings.</p>

<h3>Calling a constructor</h3>

<p>If you&#8217;re <em>not</em> passing any arguments then the parenthesis are not required. E.g.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> a <span class="sy0">=</span> <span class="kw2">new</span> Animal<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>&#8230; and this becomes:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> a <span class="sy0">=</span> <span class="kw2">new</span> Animal<span class="sy0">;</span></pre></div></div>




<p>Petty, perhaps. Still worth knowing though.</p>

<h3>var;var;var</h3>

<p>Quick and easy. Less of this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> fun <span class="sy0">=</span> <span class="nu0">123</span><span class="sy0">;</span>
<span class="kw2">var</span> tun <span class="sy0">=</span> <span class="nu0">456</span><span class="sy0">;</span>
<span class="kw2">var</span> run <span class="sy0">=</span> <span class="nu0">789</span><span class="sy0">;</span></pre></div></div>




<p>And more of this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> fun <span class="sy0">=</span> <span class="nu0">123</span><span class="sy0">,</span>
    tun <span class="sy0">=</span> <span class="nu0">456</span><span class="sy0">,</span>
    run <span class="sy0">=</span> <span class="nu0">789</span><span class="sy0">;</span></pre></div></div>




<p><em>This is why you should use a tab width of FOUR (or 4 spaces).</em></p>

<h3>Undefined &#038; Null</h3>

<p>The following is universally true in JavaScript (assuming <code>undefined</code> hasn&#8217;t been mutilated):</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">undefined <span class="sy0">==</span> <span class="kw2">null</span></pre></div></div>




<p>&#8220;So what?&#8221;, you say? Well, it means you can replace this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">if</span> <span class="br0">&#40;</span>foo <span class="sy0">===</span> undefined <span class="sy0">||</span> foo <span class="sy0">===</span> <span class="kw2">null</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="co1">//...</span>
<span class="br0">&#125;</span></pre></div></div>




<p>&#8230; With this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw1">if</span> <span class="br0">&#40;</span>foo <span class="sy0">==</span> <span class="kw2">null</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="co1">//...</span>
<span class="br0">&#125;</span></pre></div></div>




<p>If something is <code>==</code> to <code>null</code> then it is either <code>null</code> or <code>undefined</code>. Those are the only possible values.</p>

<h3>Returning undefined</h3>

<p>Not returning something from a function is the same as returning undefined, so you may as well not bother explicitly returning undefined:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">function</span> a<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span><span class="br0">&#125;</span>
<span class="kw2">function</span> b<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span> <span class="kw1">return</span><span class="sy0">;</span> <span class="br0">&#125;</span>
<span class="kw2">function</span> c<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span> <span class="kw1">return</span> undefined<span class="sy0">;</span> <span class="br0">&#125;</span>
&nbsp;
a<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">===</span> b<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// true</span>
b<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy0">===</span> c<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// true</span></pre></div></div>




<p><em>Note</em>: you should be careful with the <code>undefined</code> value as it can be changed. E.g. You can do <code>undefined = true</code> beforehand. <strong>The universe would shatter if you did that though, <em>so please don&#8217;t</em></strong>. Many libraries declare an empty (undefined) variable in an enclosed scope, which provides a real <code>undefined</code>:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span>
&nbsp;
    <span class="co1">// My private scope. They can't see me in here.</span>
&nbsp;
    <span class="kw2">var</span> undef<span class="sy0">;</span>
&nbsp;
    undef<span class="sy0">;</span> <span class="co1">// =&gt; definitely undefined</span>
&nbsp;
<span class="br0">&#125;</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>Or, more succinctly:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span>undef<span class="br0">&#41;</span><span class="br0">&#123;</span>
&nbsp;
    undef<span class="sy0">;</span> <span class="co1">// =&gt; definitely undefined</span>
&nbsp;
<span class="br0">&#125;</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// &lt;- not passing anything in!</span></pre></div></div>




<h3>Empty array values</h3>

<p>This is entirely legal in JavaScript:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> a <span class="sy0">=</span> <span class="br0">&#91;</span><span class="sy0">,,,</span><span class="st0">'foo'</span><span class="br0">&#93;</span><span class="sy0">;</span>
a<span class="br0">&#91;</span><span class="nu0">3</span><span class="br0">&#93;</span><span class="sy0">;</span> <span class="co1">// =&gt; &quot;foo&quot;</span></pre></div></div>




<p>One potential use-case of this was discussed in my recent post, <a href="http://james.padolsey.com/javascript/match-trick/">`match.()` trick</a>.</p>

<h3>Less blocks, more expressions</h3>

<p>I&#8217;m sure we&#8217;ve all seen something like this before:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">function</span> validateFoo<span class="br0">&#40;</span>foo<span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw2">var</span> regexResult <span class="sy0">=</span> <span class="co2">/^foo+$/</span>.<span class="me1">test</span><span class="br0">&#40;</span>foo<span class="br0">&#41;</span><span class="sy0">;</span>
    <span class="kw1">if</span> <span class="br0">&#40;</span>regexResult<span class="br0">&#41;</span> <span class="br0">&#123;</span>
        <span class="kw1">return</span> <span class="kw2">true</span><span class="sy0">;</span>
    <span class="br0">&#125;</span>
    <span class="kw1">return</span> <span class="kw2">false</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<p>A cleaner and more sensible solution is this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">function</span> validateFoo<span class="br0">&#40;</span>foo<span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw1">return</span> <span class="co2">/^foo+$/</span>.<span class="me1">test</span><span class="br0">&#40;</span>foo<span class="br0">&#41;</span><span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div>




<p>No fussing with <code>if</code> statements and multiple returns. You can do everything within a single return statement.</p>

<p>Another example. We want to create a function that logs a name, specified by the arguments <code>forename</code> and <code>surname</code>, but if these arguments aren&#8217;t passed then the function should use the default values, &#8220;Bob&#8221; and &#8220;Smith&#8221;, respectively:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">function</span> printName<span class="br0">&#40;</span>forename<span class="sy0">,</span> surname<span class="br0">&#41;</span> <span class="br0">&#123;</span>
&nbsp;
    <span class="kw1">if</span> <span class="br0">&#40;</span>forename <span class="sy0">==</span> <span class="kw2">null</span> <span class="sy0">||</span> forename <span class="sy0">==</span> <span class="st0">&quot;&quot;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
        forename <span class="sy0">=</span> <span class="st0">'Bob'</span><span class="sy0">;</span>
    <span class="br0">&#125;</span>
&nbsp;
    <span class="kw1">if</span> <span class="br0">&#40;</span>surname <span class="sy0">==</span> <span class="kw2">null</span> <span class="sy0">||</span> surname <span class="sy0">==</span> <span class="st0">&quot;&quot;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
        surname <span class="sy0">=</span> <span class="st0">'Smith'</span><span class="sy0">;</span>
    <span class="br0">&#125;</span>
&nbsp;
    console.<span class="me1">log</span><span class="br0">&#40;</span>forename <span class="sy0">+</span> <span class="st0">' '</span> <span class="sy0">+</span> surname<span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
<span class="br0">&#125;</span></pre></div></div>




<p>This can be condensed to:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">function</span> printName<span class="br0">&#40;</span>forename<span class="sy0">,</span> surname<span class="br0">&#41;</span> <span class="br0">&#123;</span>
&nbsp;
    forename <span class="sy0">=</span> forename <span class="sy0">||</span> <span class="st0">'Bob'</span><span class="sy0">;</span>
    surname <span class="sy0">=</span> surname <span class="sy0">||</span> <span class="st0">'Smith'</span><span class="sy0">;</span>
&nbsp;
    console.<span class="me1">log</span><span class="br0">&#40;</span>forename <span class="sy0">+</span> <span class="st0">' '</span> <span class="sy0">+</span> surname<span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
<span class="br0">&#125;</span></pre></div></div>




<p>Here, we&#8217;re using the logical OR operator (<code>||</code>) to provide a default value (right hand side) if the left hand side evaluates to false. Values that evaluate to false (i.e. &#8220;falsey&#8221;) are: An empty string (<code>""</code>), <code>null</code>, <code>undefined</code>, <code>0</code> and <code>false</code>.</p>

<p>So, this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">forename <span class="sy0">=</span> forename <span class="sy0">||</span> <span class="st0">'Bob'</span></pre></div></div>




<p>&#8230; is essentially saying: if <code>forename</code> is a truthy value, then assign <code>forename</code> to <code>forename</code> (in other words: don&#8217;t do anything), but if it is a falsey value (e.g. an empty string), then assign the string <code>"Bob"</code> to <code>forename</code>.</p>

<p>So, our new <code>printName</code> function will behave like so:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="co1">//                            -- Logged --</span>
printName<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span>                  <span class="co1">// Bob Smith</span>
printName<span class="br0">&#40;</span><span class="nu0">0</span><span class="sy0">,</span> <span class="nu0">0</span><span class="br0">&#41;</span><span class="sy0">;</span>              <span class="co1">// Bob Smith</span>
printName<span class="br0">&#40;</span><span class="kw2">false</span><span class="sy0">,</span> <span class="kw2">null</span><span class="br0">&#41;</span><span class="sy0">;</span>       <span class="co1">// Bob Smith</span>
printName<span class="br0">&#40;</span><span class="st0">'James'</span><span class="br0">&#41;</span><span class="sy0">;</span>           <span class="co1">// James Smith</span>
printName<span class="br0">&#40;</span><span class="st0">''</span><span class="sy0">,</span> <span class="st0">'Jones'</span><span class="br0">&#41;</span><span class="sy0">;</span>       <span class="co1">// Bob Jones</span>
printName<span class="br0">&#40;</span><span class="st0">'Bill'</span><span class="sy0">,</span> <span class="st0">'Jones'</span><span class="br0">&#41;</span><span class="sy0">;</span>   <span class="co1">// Bill Jones</span></pre></div></div>




<h3>Part 1 [OVER]</h3>

<p>That&#8217;s it for today. There may be a part two soon enough, depending on how useful this is to readers. I know many of you have surpassed this stage of learning, so sorry for boring you.</p>

<h3>Recommended viewing/reading</h3>

<p>Seriously, if you&#8217;re writing JavaScript as part of your job then you definitely owe it to future maintainers of your code to learning JS properly.</p>

<p><strong>EDIT</strong>: Crockford links don&#8217;t work. The <a href="http://www.youtube.com/watch?v=v2ifWcnQs6M">entire video can be seen on youtube</a> instead.

<ul>
<li><a href="http://video.yahoo.com/watch/111593/1710507">Douglas Crockford: &#8220;The JavaScript Programming Language&#8221;/1 of 4</a></li>
<li><a href="http://video.yahoo.com/watch/111594/1710553">Douglas Crockford: &#8220;The JavaScript Programming Language&#8221;/2 of 4</a></li>
<li><a href="http://video.yahoo.com/watch/111595/1710607">Douglas Crockford: &#8220;The JavaScript Programming Language&#8221;/3 of 4</a></li>
<li><a href="http://video.yahoo.com/watch/111596/1710658">Douglas Crockford: &#8220;The JavaScript Programming Language&#8221;/4 of 4</a></li>
<li><a href="http://net.tutsplus.com/tutorials/javascript-ajax/javascript-and-the-dom-series-lesson-1/">Bonus: Intro to JS &#038; the DOM</a></li>
</ul>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/terse-javascript-101-part-1/feed/</wfw:commentRss>
		<slash:comments>64</slash:comments>
		</item>
		<item>
		<title>Is negativity a problem?</title>
		<link>http://james.padolsey.com/javascript/is-negativity-a-problem/</link>
		<comments>http://james.padolsey.com/javascript/is-negativity-a-problem/#comments</comments>
		<pubDate>Wed, 12 Oct 2011 23:15:18 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=1883</guid>
		<description><![CDATA[I didn&#8217;t attend JSConf.eu, but I did catch the video of Chris Williams&#8217; speech, <a href="http://jsconf.eu/2011/an_end_to_negativity.html">An End To Negativity</a>.

At the risk of being such a bearer of negativity, I will admit to disagreeing with some of what was sold in his speech. I am not&#8230;]]></description>
			<content:encoded><![CDATA[<p>I didn&#8217;t attend JSConf.eu, but I did catch the video of Chris Williams&#8217; speech, <a href="http://jsconf.eu/2011/an_end_to_negativity.html">An End To Negativity</a>.</p>

<p>At the risk of being such a bearer of negativity, I will admit to disagreeing with some of what was sold in his speech. I am not &#8220;trolling&#8221;. I am offering my opinion, which also couples as a neutral critique.</p>

<p>I don&#8217;t feel that negativity is the problem. I think the real problem is deriving self-worth from validating or invalidating remarks from our peers. But at the same time I recognise this as an unchanging quality of human interaction.</p>

<p>If you say my code is cool, then I feel great. And if you say it&#8217;s not, then I feel upset. Whose to say which one of these reactions is the right one? Are we to dispel negativity, full stop, or are we to dispel the deriving of self-worth from such remarks? Is the positive to go as well?</p>

<p>Isn&#8217;t feeling pride of one&#8217;s own work merely an intellectual dishonesty when at the same time one will condemn both the occurrence of negativity and the feelings it rouses?</p>

<p>And let&#8217;s not forget, negativity is undeniably subjective in definition. What&#8217;s negative to you <em>isn&#8217;t</em> universally negative.</p>

<p>Maybe we should care less about the subjective polarity of the remark (good, bad, nice, mean). We should instead care about the remark&#8217;s content, i.e. its intellectual validity in the scene or thread in which it occurs.</p>

<p>Chris references an internet community that craves self-worth and thus derives it from online interactions (commenting, feedback, critique, &#8220;trolling&#8221;). This is an occurrence across the web, and isn&#8217;t something that plagues any particular sub-culture or sub-community uniquely.</p>

<p>We are only human. We are socialised animals, who have, through this socialisation, acquired a supposed weakness that makes us rely on others for validation and equally, condemnation. I know it&#8217;s wrong to steal my coworker&#8217;s food because I have been socialised to form that empathetic response that tells my mind: &#8220;No, that&#8217;s wrong.&#8221; It is via public condemnation and equally, public praise, that we acquire our values, preferences, and behavioural characteristics. Why shy away from this reality?</p>

<p>Negativity for the sake of itself is probably pointless, and I&#8217;m sure a great deal of what Chris refers to is just that &#8212; negativity without substance. But negativity (<em>remember &#8212; it&#8217;s subjectively defined!</em>) for the sake of intellectual or technical critique should be no less welcome than positivity.</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/is-negativity-a-problem/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Subclassing jQuery</title>
		<link>http://james.padolsey.com/javascript/subclassing-jquery/</link>
		<comments>http://james.padolsey.com/javascript/subclassing-jquery/#comments</comments>
		<pubDate>Sun, 11 Sep 2011 16:32:26 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=1859</guid>
		<description><![CDATA[I <a href="http://james.padolsey.com/javascript/javascript-and-dom-api-fuss/">was recently fussing over</a> how developers don&#8217;t tend to separate their DOM logic/interfaces from their JavaScript &#8220;business logic&#8221;. Fuss as I might, I left the tirade rather open-ended, and that&#8217;s because I wasn&#8217;t sure that it was really a bad thing.

Either way, since JavaScript&#8230;]]></description>
			<content:encoded><![CDATA[<p>I <a href="http://james.padolsey.com/javascript/javascript-and-dom-api-fuss/">was recently fussing over</a> how developers don&#8217;t tend to separate their DOM logic/interfaces from their JavaScript &#8220;business logic&#8221;. Fuss as I might, I left the tirade rather open-ended, and that&#8217;s because I wasn&#8217;t sure that it was really a bad thing.</p>

<p>Either way, since JavaScript and the DOM are bunking together, we may as well make it safe &#8212; OOP safe.</p>

<p>For fun, let&#8217;s see how this might look:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="coMULTI">/*
 * Word 
 * A class that encapsulates a word
 */</span>
<span class="kw2">function</span> Word<span class="br0">&#40;</span>word<span class="br0">&#41;</span> <span class="br0">&#123;</span>
&nbsp;
    <span class="kw1">this</span>.<span class="me1">setDOM</span><span class="br0">&#40;</span><span class="st0">'&lt;li&gt;&lt;/li&gt;'</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
    <span class="kw1">this</span>.<span class="me1">text</span><span class="br0">&#40;</span>word<span class="br0">&#41;</span>.<span class="me1">css</span><span class="br0">&#40;</span><span class="st0">'color'</span><span class="sy0">,</span> <span class="st0">'red'</span><span class="br0">&#41;</span><span class="sy0">;</span> <span class="co1">// jQuery methods!!!</span>
&nbsp;
<span class="br0">&#125;</span>
&nbsp;
Word.<span class="me1">prototype</span> <span class="sy0">=</span> <span class="kw2">new</span> jQuery.<span class="me1">Interface</span><span class="sy0">;</span> <span class="co1">// Magical</span></pre></div></div>




<p>So, we&#8217;re sub-classing something called <a href="https://github.com/padolsey/jQuery.Interface"><code>jQuery.Interface</code></a>, and <code>jQuery.Interface</code> is sub-classed from jQuery itself, meaning that you get all of jQuery&#8217;s methods in your object.</p>

<p><strong>This is nothing ground-breaking</strong> because we always knew we could do stuff like:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">function</span> Planet<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="co1">// Implement planet logic</span>
<span class="br0">&#125;</span>
&nbsp;
Planet.<span class="me1">prototype</span> <span class="sy0">=</span> jQuery<span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
<span class="co1">// Planet now inherits jQuery's methods!!</span></pre></div></div>




<p>But&#8230; inheriting straight from <code>jQuery()</code> won&#8217;t give you what you want. Firstly, you&#8217;ll need to mess around with populating the DOM references yourself (<code>this[0] = jQuery('&lt;div/&gt;')[0]</code> etc.), and you&#8217;d have to manage the <code>length</code> property too, and lastly you wouldn&#8217;t get all of the jQuery chainability that you&#8217;re used to. Not as you might expect it, at least:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> earth <span class="sy0">=</span> <span class="kw2">new</span> Planet<span class="sy0">;</span>
earth.<span class="me1">age</span> <span class="sy0">=</span> <span class="nu0">4540000000</span><span class="sy0">;</span>
&nbsp;
earth.<span class="me1">appendTo</span><span class="br0">&#40;</span><span class="st0">'body'</span><span class="br0">&#41;</span>.<span class="me1">age</span><span class="sy0">;</span> <span class="co1">// undefined</span></pre></div></div>




<p>It&#8217;s <code>undefined</code> because jQuery&#8217;s DOM manipulation methods will return new jQuery objects, not simply a reference to <code>this</code>, which is what we&#8217;d really like!</p>

<p>So, to make it a little easier, I created a little thing called <code>jQuery.Interface</code> which does these things for you, enabling you to have beautiful jQuery sub classes.</p>

<p>Subclassing jQuery means that your class&#8217; instances can be treated just like jQuery instances. Here&#8217;s a more realistic potential application of it:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="coMULTI">/**
 * HexColorTooltip
 * Shows a colorised tooltip when hovering over HEX colors
 */</span>
<span class="kw2">function</span> HexColorTooltip<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
&nbsp;
    <span class="kw1">this</span>.<span class="me1">offsetTop</span> <span class="sy0">=</span> <span class="nu0">10</span><span class="sy0">;</span>
    <span class="kw1">this</span>.<span class="me1">offsetLeft</span> <span class="sy0">=</span> <span class="nu0">10</span><span class="sy0">;</span>
&nbsp;
    <span class="kw1">this</span>.<span class="me1">setDOM</span><span class="br0">&#40;</span><span class="st0">'&lt;div/&gt;'</span><span class="sy0">,</span> <span class="br0">&#123;</span>
        css<span class="sy0">:</span> <span class="br0">&#123;</span>
            position<span class="sy0">:</span> <span class="st0">'absolute'</span><span class="sy0">,</span>
            border<span class="sy0">:</span> <span class="st0">'1px solid black'</span><span class="sy0">,</span>
            height<span class="sy0">:</span> <span class="nu0">50</span><span class="sy0">,</span>
            width<span class="sy0">:</span> <span class="nu0">50</span><span class="sy0">,</span>
            zIndex<span class="sy0">:</span> <span class="nu0">100</span>
        <span class="br0">&#125;</span>
    <span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
    $<span class="br0">&#40;</span><span class="st0">'body'</span><span class="br0">&#41;</span>.<span class="me1">bind</span><span class="br0">&#40;</span><span class="st0">'mousemove'</span><span class="sy0">,</span> $.<span class="me1">proxy</span><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span>e<span class="br0">&#41;</span><span class="br0">&#123;</span>
        <span class="kw1">this</span>.<span class="me1">mouseX</span> <span class="sy0">=</span> e.<span class="me1">pageX</span><span class="sy0">;</span>
        <span class="kw1">this</span>.<span class="me1">mouseY</span> <span class="sy0">=</span> e.<span class="me1">pageY</span><span class="sy0">;</span>
    <span class="br0">&#125;</span><span class="sy0">,</span> <span class="kw1">this</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
    <span class="kw1">this</span>.<span class="me1">appendTo</span><span class="br0">&#40;</span><span class="st0">'body'</span><span class="br0">&#41;</span>.<span class="me1">hide</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
&nbsp;
<span class="br0">&#125;</span>
&nbsp;
HexColorTooltip.<span class="me1">colorRegex</span> <span class="sy0">=</span> <span class="co2">/^(?:#[A-F0-9]{3}|#[A-F0-9]{6})$/i</span><span class="sy0">;</span>
&nbsp;
HexColorTooltip.<span class="me1">prototype</span> <span class="sy0">=</span> $.<span class="me1">extend</span><span class="br0">&#40;</span><span class="kw2">new</span> $.<span class="me1">Interface</span><span class="sy0">,</span> <span class="br0">&#123;</span>
    bindTo<span class="sy0">:</span> <span class="kw2">function</span><span class="br0">&#40;</span>elem<span class="br0">&#41;</span> <span class="br0">&#123;</span>
&nbsp;
        <span class="kw2">var</span> tooltip <span class="sy0">=</span> <span class="kw1">this</span><span class="sy0">;</span>
&nbsp;
        $<span class="br0">&#40;</span>elem<span class="br0">&#41;</span>.<span class="me1">each</span><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span>
&nbsp;
            <span class="kw2">var</span> t <span class="sy0">=</span> $<span class="br0">&#40;</span><span class="kw1">this</span><span class="br0">&#41;</span><span class="sy0">,</span>
                text <span class="sy0">=</span> t.<span class="me1">text</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
            <span class="kw1">if</span> <span class="br0">&#40;</span>HexColorTooltip.<span class="me1">colorRegex</span>.<span class="me1">test</span><span class="br0">&#40;</span>text<span class="br0">&#41;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
&nbsp;
                t.<span class="me1">mousemove</span><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span>
                    tooltip.<span class="me1">setColor</span><span class="br0">&#40;</span>text<span class="br0">&#41;</span>.<span class="me1">show</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span>
                <span class="br0">&#125;</span><span class="br0">&#41;</span>.<span class="me1">mouseout</span><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span>
                    tooltip.<span class="me1">hide</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span>
                <span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
            <span class="br0">&#125;</span>
&nbsp;
        <span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
    <span class="br0">&#125;</span><span class="sy0">,</span>
    setColor<span class="sy0">:</span> <span class="kw2">function</span><span class="br0">&#40;</span>color<span class="br0">&#41;</span> <span class="br0">&#123;</span>
        <span class="kw1">return</span> <span class="kw1">this</span>.<span class="me1">color</span> <span class="sy0">===</span> color <span class="sy0">?</span> <span class="kw1">this</span> <span class="sy0">:</span> 
            <span class="kw1">this</span>.<span class="me1">css</span><span class="br0">&#40;</span><span class="st0">'background'</span><span class="sy0">,</span> <span class="kw1">this</span>.<span class="me1">color</span> <span class="sy0">=</span> color<span class="br0">&#41;</span><span class="sy0">;</span>
    <span class="br0">&#125;</span><span class="sy0">,</span>
    show<span class="sy0">:</span> <span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
&nbsp;
        <span class="co1">/// Overriding jQuery.fn.show</span>
        <span class="kw1">this</span>.<span class="me1">css</span><span class="br0">&#40;</span><span class="br0">&#123;</span>
            top<span class="sy0">:</span> <span class="kw1">this</span>.<span class="me1">mouseY</span> <span class="sy0">+</span> <span class="kw1">this</span>.<span class="me1">offsetTop</span><span class="sy0">,</span>
            left<span class="sy0">:</span> <span class="kw1">this</span>.<span class="me1">mouseX</span> <span class="sy0">+</span> <span class="kw1">this</span>.<span class="me1">offsetLeft</span>
        <span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
        <span class="co1">// Call super</span>
        <span class="kw1">return</span> <span class="kw1">this</span>.<span class="me1">fn</span>.<span class="me1">show</span>.<span class="me1">call</span><span class="br0">&#40;</span><span class="kw1">this</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
    <span class="br0">&#125;</span>
<span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
<span class="co1">// USAGE</span>
<span class="kw2">var</span> tooltip <span class="sy0">=</span> <span class="kw2">new</span> HexColorTooltip<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span>
tooltip.<span class="me1">bindTo</span><span class="br0">&#40;</span><span class="st0">'span'</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p><a href="http://padolsey.net/p/jQueryInterface/repo/demo.html">See it working</a>.</p>

<p>I don&#8217;t know if others will be interested in something like this. For many developers who use jQuery this might seem completely different to the jQuery you know and love, for others, maybe you&#8217;ll see it as a move in the right direction.</p>

<p><a href="https://github.com/padolsey/jQuery.Interface"><strong>jQuery.Interface on Github</strong></a>.</p>

<p><em>Please note that it&#8217;s experimental.</em></p>

<p>Please also note that this isn&#8217;t the same as <code>jQuery.sub</code>:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">A <span class="sy0">=</span> jQuery.<span class="me1">sub</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
<span class="kw2">var</span> a <span class="sy0">=</span> <span class="kw2">new</span> A<span class="sy0">;</span>
a.<span class="me1">foo</span> <span class="sy0">=</span> <span class="st0">'Foo'</span><span class="sy0">;</span>
a<span class="br0">&#91;</span><span class="nu0">0</span><span class="br0">&#93;</span> <span class="sy0">=</span> document.<span class="me1">createElement</span><span class="br0">&#40;</span><span class="st0">'div'</span><span class="br0">&#41;</span><span class="sy0">;</span>
a.<span class="me1">length</span> <span class="sy0">=</span> <span class="nu0">1</span><span class="sy0">;</span>
&nbsp;
<span class="co1">// Chaining not reliable because some methods return a new jQ</span>
a.<span class="me1">prependTo</span><span class="br0">&#40;</span><span class="st0">'body'</span><span class="br0">&#41;</span>.<span class="me1">foo</span> <span class="co1">// =&gt; UNDEFINED</span></pre></div></div>




<p>Also, jQuery.Interface provides a helpful <code>setDOM</code> method. Fundamentally, jQuery.sub and jQuery.Interface are trying to solve slightly different problems, as far as I can see.</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/subclassing-jquery/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>JavaScript and DOM API fuss</title>
		<link>http://james.padolsey.com/javascript/javascript-and-dom-api-fuss/</link>
		<comments>http://james.padolsey.com/javascript/javascript-and-dom-api-fuss/#comments</comments>
		<pubDate>Sun, 28 Aug 2011 21:42:14 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=1854</guid>
		<description><![CDATA[You know what the DOM is, and if you don&#8217;t it&#8217;s <a href="https://developer.mozilla.org/en/DOM">easy enough to find out</a>. What isn&#8217;t so easily discovered is the answer to this: how should your code communicate with the DOM API? Should it be treated as just another API? Is it&#8230;]]></description>
			<content:encoded><![CDATA[<p>You know what the DOM is, and if you don&#8217;t it&#8217;s <a href="https://developer.mozilla.org/en/DOM">easy enough to find out</a>. What isn&#8217;t so easily discovered is the answer to this: how should your code communicate with the DOM API? Should it be treated as just another API? Is it no more deserving than, for example, a JSON web service or the web storage API?</p>

<p>What I&#8217;ve been seeing a lot of is the DOM becoming incredibly intertwined with the logic, i.e. the program becomes indifferentiable to the DOM. It all ends up being the same:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> counter <span class="sy0">=</span> document.<span class="me1">createElement</span><span class="br0">&#40;</span><span class="st0">'div'</span><span class="br0">&#41;</span><span class="sy0">;</span>
counter.<span class="me1">innerHTML</span> <span class="sy0">=</span> <span class="st0">'0'</span><span class="sy0">;</span>
document.<span class="me1">body</span>.<span class="me1">appendChild</span><span class="br0">&#40;</span>counter<span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
<span class="kw2">function</span> add<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    counter.<span class="me1">innerHTML</span><span class="sy0">++;</span>
<span class="br0">&#125;</span></pre></div></div>




<p>Where does the logic stop and the DOM representation of that logic begin?</p>

<p>This is a rudimentary example, and probably something that few of us would be caught doing, but I think similar things are done every day, and not just by beginners. This is normal code. It isn&#8217;t some beginner&#8217;s hack.</p>

<p>It wears a different mask wherever it rears its head. Here, for example, it&#8217;s under the guise of jQuery&#8217;s data API:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> alphabetList <span class="sy0">=</span> <span class="br0">&#123;</span>
    giveHigher<span class="sy0">:</span> <span class="kw2">function</span><span class="br0">&#40;</span>dom1<span class="sy0">,</span> dom2<span class="br0">&#41;</span> <span class="br0">&#123;</span>
        <span class="kw1">return</span> $<span class="br0">&#40;</span>dom1<span class="br0">&#41;</span>.<span class="me1">data</span><span class="br0">&#40;</span><span class="st0">'word'</span><span class="br0">&#41;</span> <span class="sy0">&gt;</span> $<span class="br0">&#40;</span>dom2<span class="br0">&#41;</span>.<span class="me1">data</span><span class="br0">&#40;</span><span class="st0">'word'</span><span class="br0">&#41;</span> <span class="sy0">?</span> dom1 <span class="sy0">:</span> dom2<span class="sy0">;</span>
    <span class="br0">&#125;</span><span class="sy0">,</span>
    <span class="co1">//...</span>
<span class="br0">&#125;</span><span class="sy0">;</span></pre></div></div>




<p>A shockingly high majority of <code>jQuery.data</code> uses seem to be making the mistake that I&#8217;ve demonstrated.</p>

<p>It&#8217;s subtle, not easily spotted. Right now, I&#8217;m wondering whether or not it&#8217;s acceptable.</p>

<p>For me, it goes against what I&#8217;ve picked up in programming thus far. I&#8217;m talking about best practices like separating your concerns and maintaining an OO approach, writing clean APIs to access your program&#8217;s logic (etc.). To me, the DOM is yet another representation of an object&#8217;s data. The data shouldn&#8217;t be <em>in</em> the DOM. This is how I would do it:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">function</span> Counter<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw1">this</span>.<span class="me1">dom</span> <span class="sy0">=</span> document.<span class="me1">createElement</span><span class="br0">&#40;</span><span class="st0">'div'</span><span class="br0">&#41;</span><span class="sy0">;</span>
    <span class="kw1">this</span>.<span class="me1">n</span> <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">;</span>
<span class="br0">&#125;</span>
&nbsp;
Counter.<span class="me1">prototype</span>.<span class="me1">add</span> <span class="sy0">=</span> <span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw1">this</span>.<span class="me1">dom</span>.<span class="me1">innerHTML</span> <span class="sy0">=</span> <span class="sy0">++</span><span class="kw1">this</span>.<span class="me1">n</span><span class="sy0">;</span>
<span class="br0">&#125;</span><span class="sy0">;</span></pre></div></div>




<p>The thing is, the approach here is so ridiculously similar to <code>foo.innerHTML++</code> that I really can&#8217;t tell what I&#8217;m making such a fuss over.</p>

<p>The feeling I get when I see <code>foo.innerHTML++</code> is the same as when I see:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">jQuery<span class="br0">&#40;</span><span class="st0">'div'</span><span class="br0">&#41;</span>.<span class="me1">click</span><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span>
&nbsp;
    <span class="kw1">if</span> <span class="br0">&#40;</span>$<span class="br0">&#40;</span><span class="kw1">this</span><span class="br0">&#41;</span>.<span class="me1">data</span><span class="br0">&#40;</span><span class="st0">'active'</span><span class="br0">&#41;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
        <span class="co1">// do x</span>
    <span class="br0">&#125;</span> <span class="kw1">else</span> <span class="br0">&#123;</span>
        <span class="co1">// do y</span>
    <span class="br0">&#125;</span>
&nbsp;
    $<span class="br0">&#40;</span><span class="kw1">this</span><span class="br0">&#41;</span>.<span class="me1">data</span><span class="br0">&#40;</span><span class="st0">'active'</span><span class="sy0">,</span> <span class="sy0">!</span>$<span class="br0">&#40;</span><span class="kw1">this</span><span class="br0">&#41;</span>.<span class="me1">data</span><span class="br0">&#40;</span><span class="st0">'active'</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
<span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>&#8230; instead of:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">jQuery<span class="br0">&#40;</span><span class="st0">'div'</span><span class="br0">&#41;</span>.<span class="me1">each</span><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span>
&nbsp;
    <span class="kw2">var</span> active <span class="sy0">=</span> <span class="kw2">false</span><span class="sy0">;</span>
&nbsp;
    $<span class="br0">&#40;</span><span class="kw1">this</span><span class="br0">&#41;</span>.<span class="me1">click</span><span class="br0">&#40;</span><span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span>
&nbsp;
        <span class="kw1">if</span> <span class="br0">&#40;</span>active<span class="br0">&#41;</span> <span class="br0">&#123;</span>
            <span class="co1">// do x</span>
        <span class="br0">&#125;</span> <span class="kw1">else</span> <span class="br0">&#123;</span>
            <span class="co1">// do y</span>
        <span class="br0">&#125;</span>
&nbsp;
        active <span class="sy0">=</span> <span class="sy0">!</span>active<span class="sy0">;</span>
&nbsp;
    <span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
<span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p>Opinions welcome.</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/javascript-and-dom-api-fuss/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Sonic &#8211; looping loaders</title>
		<link>http://james.padolsey.com/javascript/sonic-looping-loaders/</link>
		<comments>http://james.padolsey.com/javascript/sonic-looping-loaders/#comments</comments>
		<pubDate>Fri, 26 Aug 2011 14:48:27 +0000</pubDate>
		<dc:creator>James</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[canvas]]></category>

		<guid isPermaLink="false">http://james.padolsey.com/?p=1840</guid>
		<description><![CDATA[<a href="https://github.com/padolsey/Sonic">Sonic</a> is a small (~3k minified) JS &#8220;class&#8221; you can use to create custom loading animations. It works best with looping animations &#8212; i.e. a snake that&#8217;s trying to eat its own tail.

Sonic uses the HTML5 <code>&#60;canvas&#62;</code> element/API. It works by drawing a shape (by default&#8230;]]></description>
			<content:encoded><![CDATA[<p><a href="https://github.com/padolsey/Sonic">Sonic</a> is a small (~3k minified) JS &#8220;class&#8221; you can use to create custom loading animations. It works best with looping animations &#8212; i.e. a snake that&#8217;s trying to eat its own tail.</p>

<p>Sonic uses the HTML5 <code>&lt;canvas&gt;</code> element/API. It works by drawing a shape (by default a 6px square) at tiny intervals along a pre-defined path. You can define the path using the functions: arc, bezier and line.</p>

<p>A really basic example is a square (four lines):</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> square <span class="sy0">=</span> <span class="kw2">new</span> Sonic<span class="br0">&#40;</span><span class="br0">&#123;</span>
&nbsp;
    width<span class="sy0">:</span> <span class="nu0">100</span><span class="sy0">,</span>
    height<span class="sy0">:</span> <span class="nu0">100</span><span class="sy0">,</span>
&nbsp;
    fillColor<span class="sy0">:</span> <span class="st0">'#000'</span><span class="sy0">,</span>
&nbsp;
    path<span class="sy0">:</span> <span class="br0">&#91;</span>
        <span class="br0">&#91;</span><span class="st0">'line'</span><span class="sy0">,</span> <span class="nu0">10</span><span class="sy0">,</span> <span class="nu0">10</span><span class="sy0">,</span> <span class="nu0">90</span><span class="sy0">,</span> <span class="nu0">10</span><span class="br0">&#93;</span><span class="sy0">,</span>
        <span class="br0">&#91;</span><span class="st0">'line'</span><span class="sy0">,</span> <span class="nu0">90</span><span class="sy0">,</span> <span class="nu0">10</span><span class="sy0">,</span> <span class="nu0">90</span><span class="sy0">,</span> <span class="nu0">90</span><span class="br0">&#93;</span><span class="sy0">,</span>
        <span class="br0">&#91;</span><span class="st0">'line'</span><span class="sy0">,</span> <span class="nu0">90</span><span class="sy0">,</span> <span class="nu0">90</span><span class="sy0">,</span> <span class="nu0">10</span><span class="sy0">,</span> <span class="nu0">90</span><span class="br0">&#93;</span><span class="sy0">,</span>
        <span class="br0">&#91;</span><span class="st0">'line'</span><span class="sy0">,</span> <span class="nu0">10</span><span class="sy0">,</span> <span class="nu0">90</span><span class="sy0">,</span> <span class="nu0">10</span><span class="sy0">,</span> <span class="nu0">10</span><span class="br0">&#93;</span>
    <span class="br0">&#93;</span>
&nbsp;
<span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
square.<span class="me1">play</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
document.<span class="me1">body</span>.<span class="me1">appendChild</span><span class="br0">&#40;</span>square.<span class="me1">canvas</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p><strong><a href="http://padolsey.net/p/Sonic/repo/demo/square.html">View this example</a></strong></p>

<p>You don&#8217;t have to make up the path with a series of tiny squares though. You can do whatever you want. Another step function that comes with Sonic is fader, which draws interconnecting paths along the main path. This in combination with an arc works quite well:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span class="kw2">var</span> circle <span class="sy0">=</span> <span class="kw2">new</span> Sonic<span class="br0">&#40;</span><span class="br0">&#123;</span>
&nbsp;
    width<span class="sy0">:</span> <span class="nu0">50</span><span class="sy0">,</span>
    height<span class="sy0">:</span> <span class="nu0">50</span><span class="sy0">,</span>
    padding<span class="sy0">:</span> <span class="nu0">50</span><span class="sy0">,</span>
&nbsp;
    strokeColor<span class="sy0">:</span> <span class="st0">'#000'</span><span class="sy0">,</span>
&nbsp;
    pointDistance<span class="sy0">:</span> .01<span class="sy0">,</span>
    stepsPerFrame<span class="sy0">:</span> <span class="nu0">3</span><span class="sy0">,</span>
    trailLength<span class="sy0">:</span> .7<span class="sy0">,</span>
&nbsp;
    step<span class="sy0">:</span> <span class="st0">'fader'</span><span class="sy0">,</span>
&nbsp;
    setup<span class="sy0">:</span> <span class="kw2">function</span><span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
        <span class="kw1">this</span>._.<span class="me1">lineWidth</span> <span class="sy0">=</span> <span class="nu0">5</span><span class="sy0">;</span>
    <span class="br0">&#125;</span><span class="sy0">,</span>
&nbsp;
    path<span class="sy0">:</span> <span class="br0">&#91;</span>
        <span class="br0">&#91;</span><span class="st0">'arc'</span><span class="sy0">,</span> <span class="nu0">25</span><span class="sy0">,</span> <span class="nu0">25</span><span class="sy0">,</span> <span class="nu0">25</span><span class="sy0">,</span> <span class="nu0">0</span><span class="sy0">,</span> <span class="nu0">360</span><span class="br0">&#93;</span>
    <span class="br0">&#93;</span>
&nbsp;
<span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
circle.<span class="me1">play</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span>
&nbsp;
document.<span class="me1">body</span>.<span class="me1">appendChild</span><span class="br0">&#40;</span>circle.<span class="me1">canvas</span><span class="br0">&#41;</span><span class="sy0">;</span></pre></div></div>




<p><strong><a href="http://padolsey.net/p/Sonic/repo/demo/circle.html">View this example</a></strong></p>

<p>You can also define your own <code>step</code> function. This is really what I would recommend since the default ones (fader and square) are somewhat limited.</p>

<p>You might be thinking that I should have called it Snake instead of Sonic, but really, there are so many possibilities that Snake wouldn&#8217;t have made sense.</p>

<p>To see what Sonic can really do, <strong><a href="http://padolsey.net/p/Sonic/repo/demo/demo.html">visit the demo</a></strong>. <a href="https://github.com/padolsey/Sonic">Sonic is on github too</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://james.padolsey.com/javascript/sonic-looping-loaders/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 1.256 seconds -->
<!-- Cached page generated by WP-Super-Cache on 2012-02-04 06:09:42 -->

