<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>davidflanagan.com</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/" />
    <link rel="self" type="application/atom+xml" href="http://www.davidflanagan.com/atom.xml" />
    <id>tag:www.davidflanagan.com,2008-10-28://1</id>
    <updated>2010-07-12T23:20:24Z</updated>
    <subtitle>books for programmers</subtitle>
    <generator uri="http://www.sixapart.com/movabletype/">Movable Type 4.21-en</generator>

<entry>
    <title>canto.js: An Improved HTML5 Canvas API</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2010/07/cantojs-an-impr.html" />
    <id>tag:www.davidflanagan.com,2010://1.192</id>

    <published>2010-07-12T22:45:01Z</published>
    <updated>2010-07-12T23:20:24Z</updated>

    <summary><![CDATA[I love the &lt;canvas&gt; tag, but its 2D drawing API is intentionally minimal and unfriendly, so I've written a simple wrapper library that improves it. canto.js defines a single canto() factory function. Pass a canvas element or the id of...]]></summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>I love the &lt;canvas&gt; tag, but its 2D drawing API is intentionally minimal and unfriendly, so I've written a simple wrapper library that improves it.</p>

<p><a href="http://code.google.com/p/canto-js/downloads/list">canto.js</a> defines a single <tt>canto()</tt> factory function.  Pass a canvas element or the id of a canvas element to this function, and it returns a Canto object to you.  This Canto object is a drawing context, like the one you'd get by calling <tt>getContext('2d')</tt> on the canvas element.  The Canto object implements the 2D drawing API, so your existing canvas code should work as-is, but it also implements a number of other features.</p>

<p>One of the most important API improvements is that all Canto methods that do not have some other return value return the Canto object.  This enables <a href="http://martinfowler.com/dslwip/MethodChaining.html">method chaining</a>.  For example:</p>

<pre>
// Draw a triangle
canto("canvas_id").moveTo(100,100).lineTo(200,200,100,200).closePath().stroke();
</pre>

<p>Notice that the lineTo() method in the code above has four arguments: this is an extension that allows the single method call to draw two line segments. </p>

<p>Another useful API extension is that methods that actually perform drawing operations (such as stroke(), drawImage(), fillText(), etc.) accept a set of graphics attributes to be used for that one operation.</p>

<pre>
// Draw a colorful triangle with wide lines
canto("canvas_id").moveTo(100,100).lineTo(200,200,100,200).closePath().
    stroke({lineWidth: 15, strokeStyle: "red"});
</pre>

<p>If you've used SVG you may be familar with the compact path descriptions syntax used in the <tt>d</tt> attribute of the &lt;path&gt; element.  Canto supports this syntax, both with an svgpath() method and with individual single-letter methods like M (moveto), L (lineto), C (curveto) and so on.    Here's the SVG version of our triangle:</p>

<pre>
// Parse an SVG path string
canto("canvas_id").svgpath("M100 100 L200 200 100 200 Z").fill();
// Define path elements with methods with really short SVG-inspired names
canto("canvas_id").M(100,100).L(200,200,100,200).Z().stroke();
</pre>

<p>Other new API features include relative-coordinate methods like rmoveTo() and rlineTo() and a turtle graphics API.  A summary of the API is in the long comment at the top of the <a href="http://code.google.com/p/canto-js/source/browse/trunk/canto.js">canto.js source code</a>.</p>

<p>I've set up a  <a href="http://code.google.com/p/canto-js/">canto-js project</a> at code.google.com and have released it under the MIT license.  Comments, bug-reports and contributions are all welcome.  Test cases would be particularly nice.  I've written a few simple tests myself, and I've run Canto against <a href="http://philip.html5.org/tests/canvas/suite/tests/">Phillip Taylor's suite of canvas tests</a>.  (Results: in Firefox and Chrome, at least, Canto passes effectively all the tests that the underlying un-canto'ed 2D context pass).</p>

<p>Note that Canto currently uses getters and setters to handle graphics attributes: if you set the lineWidth property on your Canto object, the setter method  delegates to the underlying 2D context.  IE doesn't support getters and setters, so Canto does not currently work in that browser.</p>]]>
        
    </content>
</entry>

<entry>
    <title>Rough Cut of my JavaScript Book</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2010/06/rough-cut-of-my.html" />
    <id>tag:www.davidflanagan.com,2010://1.191</id>

    <published>2010-06-16T18:04:48Z</published>
    <updated>2010-06-16T18:19:48Z</updated>

    <summary>O&apos;Reilly has made a draft of the 6th edition of JavaScript: The Definitive Guide available through their Rough Cuts program. This means that you can buy online access (HTML and PDF) to the current draft of the book today, and...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>O'Reilly has made a draft of the 6th edition of <i>JavaScript: The Definitive Guide</i> available through their Rough Cuts program.  This means that you can <a href="http://oreilly.com/catalog/9781449393847/">buy online access</a> (HTML and PDF) to the current draft of the book today, and then have the print version shipped to you when it is published, for the basic cover price of the book.  (See the <a href="http://oreilly.com/roughcuts/faq.csp">FAQ</a> for more about how Rough Cuts works).</p>

<p>Online access is through <a href="http://my.safaribooksonline.com/9781449393854?portal=oreilly&cid=orm-cat-readnow-9781449393854<br />
">Safari</a>, not directly through O'Reilly, which means that you need to create an account with them in order to do this.  But that's a minor hassle if you want the latest version right away.</p>

<p>Part I of the book is finished: complete coverage of ECMAScript 5, along with completely rewritten and modernized chapters on functions, objects and classes. </p>

<p>Part II is being updated for HTML 5 and is still in progress.  The first few chapters have been pretty much completely rewritten but a number of chapters are still missing.  The Rough Cuts edition will be updated each time I finish a new chapter.  If you buy it now you get ongoing access to all the updates.</p>]]>
        
    </content>
</entry>

<entry>
    <title>Java Closures Update</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2010/05/java-closures-u.html" />
    <id>tag:www.davidflanagan.com,2010://1.190</id>

    <published>2010-05-19T16:14:02Z</published>
    <updated>2010-05-19T16:32:40Z</updated>

    <summary>Last Wednesday, I blogged about the fact that closures discussion on the Project Lambda mailing list had petered out. It appears I spoke too soon: on Friday an Oracle engineer posted a substantive strawman proposal, and followed it up with...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="java" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>Last Wednesday, I <a href="http://www.davidflanagan.com/2010/05/closures-in-jav.html">blogged about</a> the fact that closures discussion on the Project Lambda mailing list had petered out. </p>

<p>It appears I spoke too soon: on Friday an Oracle engineer posted a <a href="http://mail.openjdk.java.net/pipermail/lambda-dev/2010-May/001304.html">substantive strawman proposal</a>, and followed it up with <a href="http://mail.openjdk.java.net/pipermail/lambda-dev/2010-May/001355.html">another significant document</a> on Monday.  These have generated much discussion on the Project Lambda mailing lists, and things seem to be moving again.</p>

<p>Yesterday, Neal Gafter <a href="http://mail.openjdk.java.net/pipermail/lambda-dev/2010-May/001380.html">"read the tea leaves"</a> and surmised that Oracle has at least three engineers working on closures. </p>

<p>Its nice to know that the project isn't dead.  Of course we still don't know whether the Java 7 schedule will slip to accommodate closures or if closures will be postponed for a later release.   So the "not likely" assessment from my original post still stands.</p>]]>
        
    </content>
</entry>

<entry>
    <title>Quirks we can forget</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2010/05/quirks-we-can-f.html" />
    <id>tag:www.davidflanagan.com,2010://1.189</id>

    <published>2010-05-13T20:02:53Z</published>
    <updated>2010-05-13T20:13:40Z</updated>

    <summary>I&apos;ve just realized that there is one annoying JavaScript special-case that web developers no longer need to know about, and I don&apos;t need to document anymore. As you know, JavaScript event handlers return false to cancel the browser&apos;s default action...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>I've just realized that there is one annoying JavaScript special-case that web developers no longer need to know about, and I don't need to document anymore.</p>

<p>As you know, JavaScript event handlers return false to cancel the browser's default action for the event.  Except, that is, for the onmouseover event handler.  Because of a bug in Netscape 2.0 (I think)  we've always had to return true for that one.  Documenting this special case has become a habit for me.</p>

<p>How nice, therefore, to realize that this is now irrelevant.  The only default action associated with a mouseover event is to display the destination URL of a link.  But to prevent phishing attacks, browsers no longer allow us to cancel this default action (and no longer allow any kind of status line scripting).  Since the action can't be cancelled, the return value of onmouseover no longer matters.  Hooray!</p>

<p>So I can now just document "return false to cancel".  (Of course I still have to document e.preventDefault() for event handlers registered with addEventListener() and e.returnValue=false for event handlers registered with attachEvent(), but this is a step in the right direction.)<br />
</p>]]>
        
    </content>
</entry>

<entry>
    <title>Closures in Java 7: Not Likely</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2010/05/closures-in-jav.html" />
    <id>tag:www.davidflanagan.com,2010://1.188</id>

    <published>2010-05-12T17:22:09Z</published>
    <updated>2010-05-19T17:15:26Z</updated>

    <summary>Five months ago, I posted Closures in Java 7 After All to celebrate the announcement that JDK7 would include closures. The schedule seemed optimistic at the time, given that Mark Reinhold decided to start with a blank slate rather than...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="java" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>Five months ago, I posted <a href="http://www.davidflanagan.com/2009/12/closures-in-java-7-after-all.html">Closures in Java 7 After All</a> to celebrate the announcement that JDK7 would include closures.</p>

<p>The schedule seemed optimistic at the time, given that Mark Reinhold decided to start with a blank slate rather than adopting one of the existing closure proposals.  And sure enough, it was wildly optimistic.  The <a href="http://openjdk.java.net/projects/jdk7/milestones/">schedule</a> says that JDK 7 will be "feature complete" on June 3rd.  But the closures specification being developed by <a href="http://openjdk.java.net/projects/lambda/">Project Lambda</a> is at version 0.15</p>

<p>Activity on the Project Lambda mailing list has petered out as engineers from Sun/Oracle have become non-responsive. [<b>Update:</b> this has now changed.  See my <a href="http://www.davidflanagan.com/2010/05/java-closures-u.html">more recent post</a>.] Neal Gafter, one of the hardest-working advocates for closures in Java, has <a href="http://mail.openjdk.java.net/pipermail/lambda-dev/2010-April/001290.html">politely</a> and <a href="http://mail.openjdk.java.net/pipermail/lambda-dev/2010-April/001296.html">repeatedly</a> <a href="http://mail.openjdk.java.net/pipermail/lambda-dev/2010-May/001300.html">asked</a> for clarification of the schedule and of Oracle's commitment to closures.</p>

<p>The only <a href="http://mail.openjdk.java.net/pipermail/lambda-dev/2010-April/001299.html">answer</a> he's gotten is from Alex Buckley:</p>

<blockquote>
<p>
Schedule information for Lambda will be shared when available.
</p><p>
Resourcing decisions are out of scope for this list, but I am sure that 
any resources assigned to Lambda will be directly or indirectly visible 
on this list.
</blockquote>

<p>It seems that Alex is not permitted to speak openly about this.  But given that no activity is directly or indirectly visible through the mailing list, we can infer that there is basically no one at Oracle working on closures.  And it makes me wonder: is there anyone one at Oracle with the time and the authority to alter either the release schedule or the feature list for JDK 7?</p>]]>
        
    </content>
</entry>

<entry>
    <title>CSS opacity filter syntax for IE8</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2010/04/css-opacity-fil.html" />
    <id>tag:www.davidflanagan.com,2010://1.187</id>

    <published>2010-04-19T20:20:44Z</published>
    <updated>2010-04-19T20:46:12Z</updated>

    <summary>For a long time, IE&apos;s alternative to the CSS opacity property has been the filter property: filter: alpha(opacity=50); If you Google &quot;IE8 opacity&quot;, you&apos;ll find a number of pages (including one at quirksmode.org) telling you that Microsoft removed support for...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>For a long time, IE's alternative to the CSS opacity property has been the filter property: </p>

<pre>
filter: alpha(opacity=50);
</pre>

<p>If you Google "IE8 opacity", you'll find a number of pages (including one at quirksmode.org) telling you that Microsoft removed support for opacity in a preview release of IE8, and then put it back in, but with a new syntax.  These pages assert that in order to achieve the same half-transparent effect as above, you must write (note the -ms- prefix and the quoted value):</p>

<pre>
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
</pre>

<p>As far as I can tell, however, all of these pages are based on preview releases.  My (very simple) testing indicates that the old syntax continues to work in IE8, and there is no need to add a second non-standard property to our stylesheets for IE8.</p>

<p><a href="http://blogs.msdn.com/ie/archive/2009/02/19/the-css-corner-using-filters-in-ie8.aspx">This post at the IE blog</a> backs me up on this (scroll down to the section titled "A Pragmatic Solution")  Or at least I think it backs me up.  The post tries to explain and justify the initial change to the filter syntax but it just doesn't make much sense.</p>

<p>Someone please correct me if I'm wrong.  Are there versions of IE8 in the wild that don't support the old filter syntax?</p>]]>
        
    </content>
</entry>

<entry>
    <title>Mundane Atrocities</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2010/04/mundane-atrocit.html" />
    <id>tag:www.davidflanagan.com,2010://1.186</id>

    <published>2010-04-05T22:40:20Z</published>
    <updated>2010-04-06T22:52:23Z</updated>

    <summary>This post is just a copy of an anti-war letter to the editor I just sent to my local paper. I think it is one of my better efforts....</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="anti-war" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>This post is just a copy of an anti-war letter to the editor I just sent to my local paper. <br />
I think it is one of my better efforts.</p>
]]>
        <![CDATA[<p>To the editor:</p>

<p>We like to pretend otherwise, but we all know the truth of the old
saying: "War is Hell".  We like to believe that our soldiers are angels,
capable of fighting a clean, surgical war against an enemy with no
uniform on a battlefield with no front in villages and cities filled
with civilians. But angels don't walk this earth, and as Donald Rumsfeld
said, "You go to war with the army you have".  What we have is hundreds
of thousands of heavily armed young men, many of whom have been scared
and traumatized out of their wits, trained to kill and immersed in a
violent world.  It is no wonder then, that:</p>

<p>1) A <a href="http://collateralmurder.com/">leaked video</a> released today shows the crew of a US helicopter
shooting nearly a dozen civilians, and then shooting the man (and
his two children) who stopped to assist the wounded. We hear one of the
helicopter crew members celebrating: "Oh yeah, look at those dead
bastards!". </p>

<p>2) The military command in Kabul <a href="http://www.salon.com/news/opinion/glenn_greenwald/2010/04/05/afghanistan/index.html">admitted
on Sunday (after a two month cover-up)</a> that US special forces had
killed three civilian women (two of them pregnant) during a mistaken
February raid that also killed two Afghan government officials.</p>

<p>3) General McChrystal, commander of US forces in Afghanistan, while <a href="http://tpmmuckraker.talkingpointsmemo.com/2010/04/gen_mcchrystal_weve_shot_an_amazing_number_of_peop.php">discussing
military checkpoints with his troops</a> admitted that "In the nine-plus
months I've been here, ... we've shot an amazing number of people and
killed a number and, to my knowledge, none has proven to have been a
real threat..."</p>

<p>The General should be sickened, but not amazed, by the numbers his
troops have shot.  Atrocities like these are evil, but predictable and
mundane in war, and we need to accept this, and factor it into our
calculations. Are our wars worth the inevitable random slaughter of
(amazing numbers of) innocents? Why are we still in Afghanistan? And why
did we ever invade Iraq?</p>

<p><b>Update</b>: <a href="http://andrewsullivan.theatlantic.com/the_daily_dish/2010/04/the-lies-of-the-pentagon-ctd-3.html">must-read thoughts</a> from a US soldier deployed in Iraq about the killing depicted in the video.</p>
]]>
    </content>
</entry>

<entry>
    <title>ECMAScript 5 Talk Tonight</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2010/03/ecmascript-5-ta.html" />
    <id>tag:www.davidflanagan.com,2010://1.185</id>

    <published>2010-03-31T19:28:46Z</published>
    <updated>2010-04-01T16:27:00Z</updated>

    <summary>I&apos;ll be speaking tonight in Vancouver, BC about the new features of ECMAScript 5. Details here. I&apos;ll post the slides after I give the talk. Update: Here are the slides....</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>I'll be speaking tonight in Vancouver, BC about the new features of ECMAScript 5.<br />
<a href="http://www.meetup.com/vancouver-javascript-developers/calendar/12658072/">Details here</a>.</p>

<p>I'll post the slides after I give the talk.</p>

<p><b>Update:</b> Here are <a href="http://davidflanagan.com/Talks/es5/slides.html">the slides</a>.</p>]]>
        
    </content>
</entry>

<entry>
    <title>March Madness: 7 Years of War in Iraq</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2010/03/march-madness-7.html" />
    <id>tag:www.davidflanagan.com,2010://1.184</id>

    <published>2010-03-19T16:51:09Z</published>
    <updated>2010-03-19T17:20:28Z</updated>

    <summary>Its that time of year again! This is the 7th anniversary of the war the US started with Iraq. The score so far: Cost to US taxpayers $713 Billion US soldiers killed 4385 US soldiers wounded 31616 (though December 2009)...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="anti-war" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>Its that time of year again!</p>

<p>This is the 7th anniversary of the war the US started with Iraq.  The score so far:</p>

<dl>
<dt><a href="http://costofwar.com/">Cost to US taxpayers</a>
<dd>$713 Billion

<p><dt><a href="http://icasualties.org/">US soldiers killed</a><br />
<dd>4385</p>

<p><dt><a href="http://icasualties.org/Iraq/USCasualtiesByState.aspx">US soldiers wounded</a><br />
<dd>31616 (though December 2009)</p>

<p><dt><a href="http://iraqbodycount.org">Individually documented Iraqi civilian deaths</a><br />
<dd>About 100,000.</p>

<p><dt><a href="http://brusselstribunal.org/pdf/lancet111006.pdf">Statistically extrapolated civilian deaths</a><br />
<dd>655,000 deaths (2.5% of the population of the areas surveyed) directly and indirectly caused by the war (through July 2006).</p>

</dl>

<p>I don't think I can really describe just how angry this makes me.</p>]]>
        
    </content>
</entry>

<entry>
    <title>IE9 will have addEventListener, finally!</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2010/03/ie9-will-have-a.html" />
    <id>tag:www.davidflanagan.com,2010://1.183</id>

    <published>2010-03-16T18:19:35Z</published>
    <updated>2010-03-17T16:10:39Z</updated>

    <summary><![CDATA[ Microsoft has released a testdrive version of IE9 that includes support for: addEventListener() CSS3 Selectors CSS border-radius style for rounded corners SVG (no word on &lt;canvas&gt;, as far as I know, however) Items 2, 3 & 4 are probably...]]></summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>
Microsoft has released a <a href="http://ie.microsoft.com/testdrive/">testdrive version</a> of IE9 that includes support for:
</p>
<ol>
<li>addEventListener()
<li>CSS3 Selectors
<li>CSS border-radius style for rounded corners
<li>SVG (no word on &lt;canvas&gt;, as far as I know, however)
</ol>
<p>
Items 2, 3 & 4 are probably bigger news than item 1, but 
IE's lack of support for addEventListener() has always really irritated me.  Finally, more than a decade after it was standardized, IE will support it.  That means that by 2015 we can stop writing code that checks for addEventListener() and falls back on attachEvent().
</p>]]>
        
    </content>
</entry>

<entry>
    <title>Closures in Java 7 After All</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2009/12/closures-in-java-7-after-all.html" />
    <id>tag:www.davidflanagan.com,2009://1.182</id>

    <published>2009-12-07T22:30:49Z</published>
    <updated>2009-12-07T23:13:52Z</updated>

    <summary>I&apos;ve been focusing on JavaScript recently, so I missed this when it first came out: Closures for Java. I think it is interesting that the motivation for finally doing this is to facilitate APIs for concurrency. Sun will not be...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="java" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>I've been focusing on JavaScript recently, so I missed this when it first came out:<br />
<a href="http://blogs.sun.com/mr/entry/closures">Closures for Java</a>.  I think it is interesting that the motivation for finally doing this is to facilitate APIs for concurrency. <br />
Sun will not be using any of the existing closures proposals as a starting point, but their initial ideas are perhaps closest to the FCM (first-class methods) proposal.</p>

<p>There are <a href="http://blogs.sun.com/mr/entry/closures_qa">further details here</a> including the ominous admission by Sun that they don't feel they can get any JSRs (for closures, Project Coin, or Java 7) approved by the JCP until they resolve their dispute with Apache.  In the meantime, development of closures and the Coin extensions is happening outside of the JCP in the OpenJDK.</p>

<p> In <a href="http://mail.openjdk.java.net/pipermail/jdk7-dev/2009-November/001054.html">related news</a>, the schedule for OpenJDK7 has slipped and a final release is now due in September 2010.  Note that this is the schedule for the JDK7, not for Java 7. </p>]]>
        
    </content>
</entry>

<entry>
    <title>A module loader with simple dependency management</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2009/11/a-module-loader.html" />
    <id>tag:www.davidflanagan.com,2009://1.180</id>

    <published>2009-11-25T20:15:11Z</published>
    <updated>2009-11-25T20:37:46Z</updated>

    <summary>I&apos;ve written another version require2.js of my CommonJS module loader require() function. This one has two interesting features. First, you can &quot;pre-load&quot; modules by mapping the module filename to the module function in the require._module_function object. If you do this,...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>I've written another version <a href="http://www.davidflanagan.com/demos/require2.js">require2.js</a> of my CommonJS module loader require() function.  This one has two interesting features.</p>

<p>First, you can "pre-load" modules by mapping the module filename to the module function in the require._module_function object.  If you do this, then the module will not need to be loaded.  For example:</p>

<pre>
require._module_functions['math.js'] = function(require,exports,module) {
     // Code for the math module goes here
};
</pre>

<p>Second, this new version of require() has a require._print hook, which, if set to a suitable function, will print out the text of all modules it loads, wrapped in a function and assigned to the require._module_function map as above. You can even define a require._minimize hook if you want to do code minimization on your modules.</p>

<p>I've defined another script <a href="http://www.davidflanagan.com/demos/display_requirements.js">display_requirements.js</a> that defines suitable _print and _minimize functions.</p>

<p>So, here's the upshot.  For relatively simple applications that load modules statically at start up, use the require2.js script for loading modules.  Its inefficient, but works well during the development phase.  Then, when you're getting ready to deploy your application, load the display_requirements.js script after loading require2.js but before you actually call require() anywhere.  This will cause a big chunk of code to appear at the bottom of your web page--pre-loaded minimized versions of all the modules you used.  Cut-and-paste this code into a new file named requirements.js (or even paste it at the bottom of require2.js) and load the requirements.js script in place of the display_requirements.js script.  Now you can continue to use require() as you have always done, but it won't have to hit the network to load your modules.</p>

<p>I haven't done much deployment of real-world web applications, and am not qualified to say whether a system like this would actually be helpful in practice. But it was an easy tweak to my existing code, so there it is.</p>]]>
        
    </content>
</entry>

<entry>
    <title>CommonJS Modules implementation</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2009/11/commonjs-module.html" />
    <id>tag:www.davidflanagan.com,2009://1.179</id>

    <published>2009-11-24T23:06:30Z</published>
    <updated>2009-11-25T21:36:23Z</updated>

    <summary>I&apos;ve implemented the CommonJS Modules 1.0 specification with the code in this file. It appears to pass the compliance tests when run in Firefox and Chrome on Linux, and also when run standalone in Tracemonkey, Rhino or V8. Note that...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>I've implemented the <a href="http://commonjs.org/specs/modules/1.0.html">CommonJS Modules 1.0 specification</a> with the code in <a href="http://www.davidflanagan.com/demos/require.js">this file</a>.  It appears to pass the <a href="http://code.google.com/p/interoperablejs/">compliance tests</a> when run in Firefox and Chrome on Linux, and also when run standalone in Tracemonkey, Rhino or V8.</p>

<p>Note that this implementation does not use the namespace probing technique I described in my <a href="http://www.davidflanagan.com/2009/11/functions-as-na.html">previous post</a>.</p>

<p><b>Update:</b> One of the things that really surprised me when testing my implementation was to discover that the CommonJS spec requires (this is not explicit in the specification text, but it is explicit in the conformance tests) the require() function to return the actual exports object of a module, and not make a defensive copy of it.</p>

<p>Suppose a program includes module A which includes modules B and C.  Module C can require B and then add, replace, or remove methods from B's API.  Later, when the program includes Module B directly, it will get the modified version of B.  In order to correctly use this modified module B, the programmer will have to read the documentation for module C!</p>

<p><b>Update 2:</b> There are great comments to this post, including a link to <a href="http://lucassmith.name/2009/11/commonjs-require-api-is-a-poor-fit-for-client-side-js.html">Luke Smith's blog post</a> that argues that the synchronous nature of CommonJS modules is not a good fit for client-side scripting.  In response I wanted to make clear that I posted this code because I thought it was interesting, not because I think that client-side programmers should go out and start using it right away.</p>]]>
        
    </content>
</entry>

<entry>
    <title>Functions as Namespaces, and How to Peek Inside</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2009/11/functions-as-na.html" />
    <id>tag:www.davidflanagan.com,2009://1.178</id>

    <published>2009-11-21T07:15:21Z</published>
    <updated>2009-11-21T08:02:53Z</updated>

    <summary> It has become common in modern JavaScript programming to use functions as namespaces. If you put your code inside a function, then your variables and functions are local to the containing function and do not clutter up the global...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>
It has become common in modern JavaScript programming to use functions as namespaces.  If you put your code inside a function, then your variables and functions are local to the containing function and do not clutter up the global scope.
</p>
<pre>
var value = (function() {  // Wrapper function creates a local scope or namespace
    // your code goes here
    return value;  // Export a value from the namespace
)());  // Invoke the wrapper function to run your code      
</pre>
<p>
Now suppose that you have some JavaScript code as a string--you've just loaded it using XMLHttpRequest, for example.  You're going to evaluate the code, and you might want to evaluate it in a namespace so that it doesn't define functions and variables in the global scope.  This is easy: just wrap it in a function before evaluating it.  In this case, the Function() constructor is even more handy than the eval() function:
</p>
<pre>
var code = ....;  // A string of JS code to evaluate
var f = new Function(code);   // Wrap it in a function
f();    // And run the function
</pre>
<p>
The problem with doing this is that the function creates a sealed namespace and we can't see what is inside.  If the code defines something useful like a function or a class, we can't access it, and it does us no good.
</p><p>
Here's a trick I've just discovered.  (I'm sure someone else has thought of this, but I haven't seen it used or described elsewhere).  Before you wrap your code in a function add this line to it:
</p>
<pre>
return function(s) { return eval(s); };
</pre>
<p>
Now, when you invoke the wrapper function, it returns this evaluator function to you.  The returned function evaluates a string <i>in the scope of the namespace</i>, so you can use it to peek into the namespace and extract whatever values you want!
</p><p>
If your string of code defines a constructor function named Set() that you want to use, you can run the code in a namespace and then extract f from the namespace like this:
</p>
<pre>
var code = readFile("Set.js");  // A string of JS code to evaluate
// Define and invoke a wrapper function with special suffix code.
// The return value is a namespace evaluator function and we treat
// it as a namespace object.
var setns = new Function(code + "return function(s) { return eval(s); };")(); 
var Set = setns("Set");  // Import the Set function from the namespace.
var s = new Set();  // Use the class we just imported
</pre>
<p>
And what if there are 3 values you want to extract from the namespace?
</p>
<pre>
// Extract an object containing 3 values from the namespace
var sets = setns('{Set:"Set", BitSet:"BitSet", MultiSet:"MultiSet"}');
var bs = new sets.BitSet();
</pre>
<p>
I've defined a namespace() function for loading code and doing this kind of namespacing automatically: </p>]]>
        <![CDATA[<pre>
/*
 * Load modules of code by enveloping them in a function and executing
 * the function: then they don't pollute the global namespace (unless they
 * assign to undeclared variables, but ES5 strict mode will prevent that.)
 * The wrapper function we create returns an evaluator function that 
 * evals a string inside the namespace. This evaluator function is the
 * return value of namespace() and provides read access to the symbols 
 * defined inside the namespace.
 */
function namespace(url) {
    if (!namespace.cache) namespace.cache = {};  // First call only
    if (!namespace.cache.hasOwnProperty(url)) {  // Only load urls once
        var code = gettext(url);           // Read code from url
        var f = new Function(code +        // Wrap code, add a return value
                             "return function(s) { return eval(s); };");
        namespace.cache[url] = f.call({}); // Invoke wrapper, cache evaluator
    }
    return namespace.cache[url];  // Return cached evaluator for this namespace
}

/* Return the text of the specified url, script element or file */
function gettext(url) {
    if (typeof XMLHttpRequest !== "undefined") { // Running in a browser
        if (url.charAt(0) == '#') {              // URL names a script tag
            var tag = document.getElementById(url.substring(1));
            if (!tag || tag.tagName != "SCRIPT")
                throw new Error("Unknown script " + url);
            if (tag.src) return gettext(tag.src);// If it has a src attribute
            else return tag.text;                // Otherwise use script content
        }
        else {                                   // Load file with Ajax
            var req = new XMLHttpRequest();
            req.open("GET", url, false);         // Asynchronous get
            req.send(null);
            return req.responseText;             // Error handling?
        }
    }
    else if (typeof readFile == "function") return readFile(url);  // Rhino
    else if (typeof snarf == "function") return snarf(url); // Spidermonkey
    else if (typeof read == "function") return read(url);   // V8
    else throw new Error("No mechanism to load module text");
}
</pre>
<p>
You can also find these functions in <a href="/demos/namespace/namespace.js">namespace.js</a>.  I've written a simple <a href="/demos/namespace/nstest.html">demo</a>.  It doesn't do anything interesting--just alerts 256.  But if you look at the code, you'll see that it loads and namespaces 4 chunks of code.
</p><p>
If you're a Python programmer you may be thinking that this technique would be useful for implementing a Python-style "from foo import bar" type module system.  I've been thinking the same thing and I'm working on it (but the code isn't ready to share).  The shortcoming, of course, is that there is no way to enumerate and import all the symbols defined in a namespace, so we can't simulate Python's "import *"
</p>]]>
    </content>
</entry>

<entry>
    <title>Google Closure Library and Optimizer</title>
    <link rel="alternate" type="text/html" href="http://www.davidflanagan.com/2009/11/google-closure.html" />
    <id>tag:www.davidflanagan.com,2009://1.177</id>

    <published>2009-11-06T20:30:40Z</published>
    <updated>2009-11-06T21:11:52Z</updated>

    <summary> Google has open-sourced the javascript library and optimizer they use in gmail and other web applications. They call it &quot;Closure&quot; and you can read about it here. While the optimizer looks very cool, I think the library is most...</summary>
    <author>
        <name>David</name>
        
    </author>
    
        <category term="javascript" scheme="http://www.sixapart.com/ns/types#category" />
    
    
    <content type="html" xml:lang="en" xml:base="http://www.davidflanagan.com/">
        <![CDATA[<p>
Google has open-sourced the javascript library and optimizer they use in gmail and other web applications.  They call it "Closure" and you can <a href="http://code.google.com/closure/">read about it here</a>.
</p><p>
While the optimizer looks very cool, I think the library is most impressive.  Its a really large code base, and at least some of it has been thoroughly field-tested in gmail and similar applications.  You can get the code like this:
</p>
<pre>
svn checkout http://closure-library.googlecode.com/svn/trunk/ closure-library-read-only
</pre>

<p>
The closure library is intended to be used with the closure optimizer which removes unused code, so the APIs are broad with lots of methods--there is no sense that the closure developers were skimping on API in order to pack everything into a small download bundle.  Also, and perhaps for the same reason, the code is not full of micro-optimizations.  Compared to the jQuery and YUI code (for example) the Closure code is straightforward and easy to understand. 
</p>]]>
        
    </content>
</entry>

</feed>
