<?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/"
	>

<channel>
	<title>Mike G in NYC &#187; JavaScript</title>
	<atom:link href="http://www.lovemikeg.com/blog/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.lovemikeg.com/blog</link>
	<description>Mike G's Thoughts on the Web, Code, and Life in The City</description>
	<pubDate>Sun, 28 Jun 2009 04:41:16 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>The Factory Pattern in JavaScript</title>
		<link>http://www.lovemikeg.com/blog/2009/06/26/the-factory-pattern-in-javascript/</link>
		<comments>http://www.lovemikeg.com/blog/2009/06/26/the-factory-pattern-in-javascript/#comments</comments>
		<pubDate>Fri, 26 Jun 2009 23:08:00 +0000</pubDate>
		<dc:creator>mikeg</dc:creator>
		
		<category><![CDATA[Code]]></category>

		<category><![CDATA[Design Patterns]]></category>

		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.lovemikeg.com/blog/?p=424</guid>
		<description><![CDATA[We could also call this article, &#8220;JavaScript Constructors Considered Harmful.&#8221;
I recall reading a post recently which describes factory methods as a best practice. I can&#8217;t tell you how thrilled this made me as I&#8217;ve been advocating this for years, even to the extreme view that the author used as an example: new Form(). 
In my [...]]]></description>
			<content:encoded><![CDATA[<p>We could also call this article, &#8220;JavaScript Constructors Considered Harmful.&#8221;</p>
<p>I recall reading <a href="http://ossigeno.sourceforge.net/blog/content/article/factory-for-everything">a post</a> recently which describes factory methods as a best practice. I can&#8217;t tell you how thrilled this made me as I&#8217;ve been advocating this for years, even to the extreme view that the author used as an example: new Form(). </p>
<p>In <a href="/blog/2009/05/06/upcoming-talk-object-oriented-javascript">my most recent talk at AJAXWorld 2009</a>, I briefly discussed the Factory Pattern as it applies to JavaScript. In my talk, I took a jump away from simple best practices and gave a real-world problem/solution approach to factories in JavaScript. </p>
<p><strong>The problem:</strong> JavaScript will allow you to invoke constructor functions as normal functions.<br />
<strong>The simplest possible solution:</strong> Use a factory method to instantiate everything.</p>
<p>My personal recommendation is to only use constructors internally and to never expose constructors directly.</p>
<h3>What the hell? Why are constructors so bad?</h3>
<p>Constructors in JavaScript are bad because of one thing, and it&#8217;s the same thing that is at the heart of almost all of JavaScript&#8217;s problems: implied global scope. </p>
<p>Consider the following code:</p>
<pre class="prettyprint">
// Define our constructor function
var Person = function (name, location) {
    this.name = name;
    this.location = location;
};

// Create one instance of Person
var mike = new Person('Mike G.', 'NYC');

// Create another instance of Person
var alex = Person('Alex H.', 'NYC');
</pre>
<p>Did you spot my mistake? I omitted the <samp>new</samp> keyword while creating the second <samp>Person</samp> instance. If you run this code in any web browser, you&#8217;ll notice that the browser will redirect you immediately upon running it. </p>
<p>This is a big problem.</p>
<p>When you invoke any function with the <samp>new</samp> keyword, it treats it as a constructor and executes within the context of the newly created instance. When you invoke any function without the <samp>new</samp> keyword, it treats it as a normal function and executes within the context in which the function was defined (typically <samp>window</samp>). </p>
<p>With that knowledge, go back and re-read the code and tell me why the browser redirects now&#8230; </p>
<h3>Factories save the day</h3>
<p>The easiest way to fix this problem is to use a factory. Here&#8217;s my proposed solution:</p>
<pre class="prettyprint">
var Person = function (name, location) {
    return Person.factory(name, location);
};

Person.factory = function (name, location) {
    return new Person(name, factory);
};
</pre>
<p>One of JavaScript&#8217;s brilliant features is that Constructors can have return values. In this example, my constructor is returning the result of the <samp>Person.factory</samp> call.</p>
<p>Now it doesn&#8217;t matter how you invoke this constructor. You can use <samp>new</samp> or you can omit it. This is defensive code and it&#8217;s JavaScript done right.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lovemikeg.com/blog/2009/06/26/the-factory-pattern-in-javascript/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Synchronous Execution in JavaScript</title>
		<link>http://www.lovemikeg.com/blog/2009/05/27/synchronous-execution-in-javascript/</link>
		<comments>http://www.lovemikeg.com/blog/2009/05/27/synchronous-execution-in-javascript/#comments</comments>
		<pubDate>Wed, 27 May 2009 08:06:15 +0000</pubDate>
		<dc:creator>mikeg</dc:creator>
		
		<category><![CDATA[Code]]></category>

		<category><![CDATA[Design Patterns]]></category>

		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.lovemikeg.com/blog/?p=406</guid>
		<description><![CDATA[Complex front-end web applications generally consist of many components which are initialized and configured at load time. What I&#8217;ve come to find out quite recently is that some browsers simply can&#8217;t handle too many things going on at once (eg: IE6 and lots of DOM operations). 
As a small experiment, I decided to write a [...]]]></description>
			<content:encoded><![CDATA[<p>Complex front-end web applications generally consist of many components which are initialized and configured at load time. What I&#8217;ve come to find out quite recently is that some browsers simply can&#8217;t handle too many things going on at once (eg: IE6 and lots of DOM operations). </p>
<p>As a small experiment, I decided to write a quick system that allows for synchronous execution of functions. In other words, a queue of functions which executes in order and only allows one component to execute at a time. My hopes are that by grouping the initialization routines into segments, the page will become more stable as the effort will be more distributed.</p>
<p>At first the solution sounds simple: just create an array of functions you wish to run, loop over the array and execute each function along the way.</p>
<p>Of course, it just doesn&#8217;t work like that. Function 0 may be complex and take much longer to execute than function 1. In this case, the order of function definition matters very little when compared to the time the function takes to execute.</p>
<p>If you&#8217;re stumped, I&#8217;ve posted <a href="http://code.google.com/p/lovemikeg/source/browse/#svn/synchronous-executor">the solution and a demonstration</a> to the lovemikeg code repository. The breakdown works like this:</p>
<ol>
<li>Like the first proposed solution, an array is used to store functions in the queue.</li>
<li>A next() method is defined which executes the next available function in the queue (if any).</li>
<li>Whenever a function is added to the queue it&#8217;s wrapped in a function which when executed defines another function passed to window.setTimeout. This inner function executes the original function and then immediately calls the next() method</li>
</ol>
<p>It&#8217;s basic I know: There&#8217;s no prioritization&#8230; or scope overriding&#8230; or configurable parameters. This is however, a great example of the power of anonymous functions and closure in JavaScript. I&#8217;m not confident that this will translate over to other languages well, but the pattern certainly will.</p>
<p>Whether this turns out to be a good solution for distributing initialization effort has yet to be determined. As I learn more, I&#8217;ll update this post. </p>
<p><strong>Update May 27, 2009: </strong> Looks like I&#8217;m not the only one thinking about this topic:  <a href="http://cavaliere.org/async">http://cavaliere.org/async</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.lovemikeg.com/blog/2009/05/27/synchronous-execution-in-javascript/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Upcoming Talk: Object Oriented JavaScript</title>
		<link>http://www.lovemikeg.com/blog/2009/05/06/upcoming-talk-object-oriented-javascript/</link>
		<comments>http://www.lovemikeg.com/blog/2009/05/06/upcoming-talk-object-oriented-javascript/#comments</comments>
		<pubDate>Wed, 06 May 2009 08:28:44 +0000</pubDate>
		<dc:creator>mikeg</dc:creator>
		
		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[Talks]]></category>

		<guid isPermaLink="false">http://www.lovemikeg.com/blog/?p=401</guid>
		<description><![CDATA[I will be presenting Object Oriented JavaScript at AjaxWorld this year. 
You can find the talk&#8217;s abstract below. I&#8217;m still working on the slides so if there is anything you would like me to touch on, I&#8217;m open to suggestions.
From the Sessions page:
JavaScript has taken a lot of heat over the last few years for [...]]]></description>
			<content:encoded><![CDATA[<p>I will be presenting <em>Object Oriented JavaScript</em> at <a href="http://ajaxworld.com">AjaxWorld</a> this year. </p>
<p>You can find the talk&#8217;s abstract below. I&#8217;m still working on the slides so if there is anything you would like me to touch on, I&#8217;m open to suggestions.</p>
<p>From the <a href="http://ajaxworld.com/event/sessions">Sessions</a> page:</p>
<blockquote><p>JavaScript has taken a lot of heat over the last few years for various reasons, one of which being it&#8217;s lack of proper object orientation. On the contrary, JavaScript is fully object-oriented, supports many types inheritance and also supports member visibility. This talk will explore the JavaScript programming language and will demonstrate several practical design patterns you can use in your JavaScript/Ajax application today.</p></blockquote>
<p>On a somewhat related note, I really need to update my speaking bio and head shots. Any photographers in the audience?</p>
<p>Update: Here are the slides for those who missed out.</p>
<div style="width:425px;text-align:left" id="__ss_1628090"><a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" href="http://www.slideshare.net/mgirouard/object-oriented-javascript-1628090?type=presentation" title="Object Oriented JavaScript">Object Oriented JavaScript</a><object style="margin:0px" width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=objectorientedjavascript-090623151723-phpapp01&#038;stripped_title=object-oriented-javascript-1628090" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=objectorientedjavascript-090623151723-phpapp01&#038;stripped_title=object-oriented-javascript-1628090" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed></object>
<div style="font-size:11px;font-family:tahoma,arial;height:26px;padding-top:2px;">View more <a style="text-decoration:underline;" href="http://www.slideshare.net/">presentations</a> from <a style="text-decoration:underline;" href="http://www.slideshare.net/mgirouard">Michael Girouard</a>.</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.lovemikeg.com/blog/2009/05/06/upcoming-talk-object-oriented-javascript/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Review: Learning Dojo by Peter Svensson</title>
		<link>http://www.lovemikeg.com/blog/2009/02/23/review-learning-dojo-by-peter-svensson/</link>
		<comments>http://www.lovemikeg.com/blog/2009/02/23/review-learning-dojo-by-peter-svensson/#comments</comments>
		<pubDate>Tue, 24 Feb 2009 02:52:24 +0000</pubDate>
		<dc:creator>mikeg</dc:creator>
		
		<category><![CDATA[Code]]></category>

		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[Opinion]]></category>

		<category><![CDATA[Reviews]]></category>

		<category><![CDATA[books]]></category>

		<guid isPermaLink="false">http://www.lovemikeg.com/blog/?p=346</guid>
		<description><![CDATA[&#8230; or How to Write a Good JavaScript Book
It&#8217;s widely known that the vast majority of JavaScript books that exist are bad. Unfortunately, I have another one to add to the list: Learning Dojo by Peter Svensson.
I fought with myself over whether or not it is a good idea to post this review. I&#8217;m afraid [...]]]></description>
			<content:encoded><![CDATA[<p>&#8230; or <em>How to Write a Good JavaScript Book</em></p>
<p>It&#8217;s widely known that the vast majority of JavaScript books that exist are bad. Unfortunately, I have another one to add to the list: Learning Dojo by Peter Svensson.</p>
<p>I fought with myself over whether or not it is a good idea to post this review. I&#8217;m afraid that this review may come across as an attack on the author, the publisher, or the reviewers of the book. Instead of looking at all of the errors in the book one-by-one, I am going to try to write an exhortatory post so I can better communicate what I would expect in any JavaScript book in this class.</p>
<p>To be fair, I don&#8217;t think that the blame for the book&#8217;s poor quality should be entirely on the author. From what I can gather simply from reading it, I would say this book was rushed and not properly reviewed for quality or accuracy. Also, I&#8217;m a purest when it comes to the web; so when I see [what I perceive to be] an outright dismissal of best practices, I start to get a little judgmental. Sorry, I can&#8217;t help it.</p>
<p>So, after over a month, I have finished reading the book cover-to-cover. I&#8217;ll admit that I part of the reason why it took me so long to get through the book was because I  lost interest about halfway through. Chapter 6, Layouts (linked below) is long, tedious and goes against nearly everything I stand for when it comes to building web pages. I simply had to keep putting the book down. Before I get ahead of myself, let me start off start off at the beginning and work our way down.</p>
<h3>Source code should always be carefully formatted</h3>
<p>Whenever someone asks me to critique a web site they have built, one of the first things I do is view the HTML source. If the developer has taken the time to make sure that the code indented properly and consistently spaced, I see that as someone who really cares about the quality of their project. I see it as a sign of a <em>craftsman</em> at work. </p>
<p>In the real world, this is a &#8220;nice to have&#8221; as it doesn&#8217;t really matter much &#8212; just as long as the page functions correctly, I don&#8217;t have much to complain about. In the world of tech books, however, properly formatted source code is a <em>requirement</em>. Remember, people learn from the source. Chances are, people will copy that down character-by-character and think that it&#8217;s the right way to do it.</p>
<p>Listen, JavaScript source code can be complex enough by itself. It&#8217;s an author&#8217;s responsibility to make sure that it&#8217;s as clear as possible so that good habit patterns are established from the jump. In nearly every source code listing in the book, I found something inconsistent, oddly spaced, full of errors, or simply impossible to read. This to me is completely unacceptable and was one of the first things I noticed while reading this book.</p>
<h3>Even JavaScript books should encourage web standards</h3>
<p>Almost every HTML document in the book was invalid. This was mainly due to the fact that Dojo itself encourages the use of custom attributes. Some may argue that there&#8217;s nothing wrong with this practice, especially when making use of a custom DOCTYPE. What&#8217;s worse is that the author made no effort to provide any alternative techniques let alone even discuss the dangers of deliberately writing invalid code. This may have been excusable ten years ago, but not in this day and age.</p>
<p>At the very least, I believe the author should have demonstrated an alternative technique for defining custom attributes &#8212; for example, using a combination of <samp>dojo.addOnLoad</samp> and <samp>setAttribute</samp>, or even better: not use custom attributes at all and use each respective dijit&#8217;s constructor.</p>
<h3><samp>eval</samp> is Evil</h3>
<p>There is only one circumstance where the <samp>eval</samp> function should be used: parsing an Ajax response; and that&#8217;s only allowed after the response has been properly sanitized via a regular expression.</p>
<p>This is a concept which is well known and documented in every programming language with an <samp>eval</samp> function. Nothing further needs to be said about this.</p>
<h3>JavaScript is deep; spend extra time on complex topics</h3>
<p>Because I&#8217;m also working on a post where I explain closures in JavaScript, I was very pleased to see that the author had taken the time out to explain them in this book. Unfortunately, the explanation of closures in Chapter 2 left me more confused than when I had started &#8212; and I&#8217;m quite familiar with the topic. </p>
<p>Admittedly, the problem of JavaScript closures is two-fold: closures are incredibly abstract and secondly, almost nobody knows JavaScript&#8217;s full capabilities as a <a href="http://en.wikipedia.org/wiki/Functional_programming">functional programming language</a>. Source code helps to illuminate the complex topics, but a practical example should be carefully chosen. Two examples are given by the author, however one is broken and the other is completely misleading. This book is better off not even mentioning closures at all.</p>
<p>It also should be mentioned that your explanations should be technically correct. Let me quote the author&#8217;s explanation of how Ajax works:</p>
<blockquote><p>In practices, what happens is that the browser opens a new iframe with zero height and width. Each iframe is capable of loading and posting data independently of each other, and so the accesses of the &#8216;invisible&#8217; iframe will not affect the main page to be reloaded.</p></blockquote>
<p>I&#8217;m not sure if the user was explaining how Dojo does Ajax or if he was trying to simplify the topic into familiar language, but the explanation is just wrong. This makes for a wonderful segue into the next, and equally important topic: proper terminology.</p>
<h3>Never use improper terminology &#8212; ever</h3>
<p>Programming is as much of a science as it is an art form, and as a result any sort of educational material should make use of proper terminology. In areas of introducing new concepts, it&#8217;s quite acceptable to use an analogy or reference another topic in order to build a frame of reference. For example, the author likens JavaScript objects to associative arrays. This is great because the name/value structure of objects in JavaScript are <em>very similar</em> to associative arrays; however, they are not the same thing. All throughout the book, the author uses the term &#8220;associative array&#8221; when he really means &#8220;use an object-literal as an associative array.&#8221;</p>
<p>In other instances, the terms &#8220;parameter&#8221;, &#8220;property&#8221;, and &#8220;attribute&#8221; are used interchangeably when referring to HTML attributes. Switching up vocabulary is just as dangerous as using incorrect terminology. Why? Because it makes you sound like you don&#8217;t know what you&#8217;re talking about. This is really bad when the people you teach start parroting this back. </p>
<h3>Concluding Thoughts</h3>
<p>There you have it, five simple things to keep in mind while reading this book or while attempting to write your own. I&#8217;ll say it again, I don&#8217;t want to attack anyone involved in the publishing of this book. That said, I won&#8217;t apologize for my response. The above mentioned topics are basic and there is simply no excuse for them to have slipped through the cracks.</p>
<p>At the time of this writing, absolutely no <a href="http://www.packtpub.com/support/book/tutorial-for-building-interactive-interfaces-with-dojo">errata</a> has been published for this book. This only adds to the reasons why I simply cannot recommend this book anyone, regardless skill level.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.lovemikeg.com/blog/2009/02/23/review-learning-dojo-by-peter-svensson/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Teaser: Learning Dojo by Peter Svensson</title>
		<link>http://www.lovemikeg.com/blog/2009/01/14/teaser-learning-dojo-by-peter-svensson/</link>
		<comments>http://www.lovemikeg.com/blog/2009/01/14/teaser-learning-dojo-by-peter-svensson/#comments</comments>
		<pubDate>Wed, 14 Jan 2009 22:02:30 +0000</pubDate>
		<dc:creator>mikeg</dc:creator>
		
		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[Opinion]]></category>

		<category><![CDATA[Reviews]]></category>

		<guid isPermaLink="false">http://www.lovemikeg.com/blog/?p=318</guid>
		<description><![CDATA[Yesterday I received a review copy of Learning Dojo by Peter Svensson (via Packt Publishing). Over the next week or two, I&#8217;ll be reading it and taking some notes on the book&#8217;s content. When I&#8217;m done, I&#8217;ll follow up with an official book review.
Believe it or not, I&#8217;m actually looking forward to this book as [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday I received a review copy of <a href="http://www.packtpub.com/tutorial-for-building-interactive-interfaces-with-dojo/book">Learning Dojo by Peter Svensson</a> (via <a href="http://www.packtpub.com/">Packt Publishing</a>). Over the next week or two, I&#8217;ll be reading it and taking some notes on the book&#8217;s content. When I&#8217;m done, I&#8217;ll follow up with an official book review.</p>
<p>Believe it or not, I&#8217;m actually looking forward to this book as <a href="http://www.dojotoolkit.com/" title="The Dojo JavaScript Toolkit homepage">Dojo</a> is one of the few libraries that I haven&#8217;t spent a great deal of time with. I&#8217;m certainly a fan of component libraries like Dojo, <a href="http://developer.yahoo.com/" title="The Yahoo! User Interface Library home page">YUI</a>, <a href="http://prototypejs.org/" title="The Prototype JavaScript Framework home page">Prototype</a> (YUI being my favorite) so at least the territory is familiar. I do remember there being a few things about the library that were immediate turn-offs to me, but seeing a few best practices mentioned in the book (that&#8217;s the secret to my heart, by the way) and also after the <a href="http://devzone.zend.com/article/3545-Dojo-and-Zend-Framework-Partnership-Announcement">Dojo + Zend partnership announcement</a> of last year, I think giving the library a second try is in order.</p>
<h3>Chapter Summary</h3>
<ol>
<li>Introduction to Dojo</li>
<li>Useful JavaScript and Dojo Tricks</li>
<li>Basic Dijit Knowledge</li>
<li>Ajax Communication</li>
<li>Forms</li>
<li>Layout (<a href="http://www.packtpub.com/files/learning-dojo-sample-chapter-6-layout.pdf">PDF</a>)</li>
<li>Data, Trees, and Grids</li>
<li>Real-World Dojo</li>
</ol>
<p>The book itself seems to offer a pretty good introduction to the library (and JavaScript too). Check out the <a href="http://www.packtpub.com/article/tutorial-for-building-interactive-interfaces-with-dojo-table-of-contents">table of contents</a> and see for yourself.</p>
<div class="update">
<p>Update: You can check out <a href="http://www.packtpub.com/files/learning-dojo-sample-chapter-6-layout.pdf">Chapter 6: Layout</a> for free on the PacktPub website.</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.lovemikeg.com/blog/2009/01/14/teaser-learning-dojo-by-peter-svensson/feed/</wfw:commentRss>
		</item>
		<item>
		<title>A Week in JavaScript Patterns: Lazy Function Definition</title>
		<link>http://www.lovemikeg.com/blog/2008/08/21/a-week-in-javascript-patterns-lazy-function-definition/</link>
		<comments>http://www.lovemikeg.com/blog/2008/08/21/a-week-in-javascript-patterns-lazy-function-definition/#comments</comments>
		<pubDate>Thu, 21 Aug 2008 11:53:06 +0000</pubDate>
		<dc:creator>mikeg</dc:creator>
		
		<category><![CDATA[Code]]></category>

		<category><![CDATA[Design Patterns]]></category>

		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.lovemikeg.com/blog/?p=205</guid>
		<description><![CDATA[Lazy Function Definition is a pattern of functional JavaScript programming, similar to Load Time Configuration. The key difference is that the final function value isn&#8217;t configured at load time, but rather upon the first invocation of the function.
The Lazy Function Definition pattern was discovered and named by Peter Michaux.
Motivation
Generally there are two main reasons for [...]]]></description>
			<content:encoded><![CDATA[<p>Lazy Function Definition is a pattern of functional JavaScript programming, similar to <a href="/blog/2008/08/18/a-week-in-javascript-patterns-load-time-configuration/">Load Time Configuration</a>. The key difference is that the final function value isn&#8217;t configured at load time, but rather upon the first invocation of the function.</p>
<p>The Lazy Function Definition pattern was discovered and named by <a href="http://peter.michaux.ca/article/3556">Peter Michaux</a>.</p>
<h3>Motivation</h3>
<p>Generally there are two main reasons for wanting to defer defining functions until a later time (although with any pattern, many other applications exist):</p>
<ol>
<li>Resources required for a function to be fully defined are not available until the page fully loads or until a user-driven event (for example, determining page scroll).</li>
<li>The resources created by defining the function are particularly taxing and may not even be needed (for example <a href="http://mattsnider.com/javascript/xbrowser-event-handling/">attaching event handlers</a>).</li>
</ol>
<h3>Implementation</h3>
<p>The Lazy Function Definition solves these problems by defining resources upon the first invocation of the function and then redefining itself so that they are not recreated during subsequent calls. All resources are stored via closure so they remain available to the inner function (which becomes the new definition for the outer function).</p>
<pre class="prettyprint">
var getResource = function () {
    var resource, counter;

    resource = 'foo';
    counter = 0;

    getResource = function () {
        return resource + ' has been accessed ' + (++counter) + ' times';
    };

    return getResource();
};
</pre>
<p>In the code above, a <samp>getResource</samp> function is defined. When the function is called the first time, <samp>resource</samp> and <samp>counter</samp> are created to store important information which is needed in future calls to <samp>getResource</samp>. </p>
<p>The function which immediately follows <em>redefines</em> the original <samp>getResource</samp> function, but because resource <samp>resource</samp> and <samp>counter</samp> are defined in the same scope as the inner function, they remain available.</p>
<p>Finally, the new <samp>getResource</samp> is executed and it&#8217;s value is returned. Now any future calls to <samp>getResource</samp> will use the inner function. </p>
<h3>Conclusion</h3>
<p>The Lazy Function Definition pattern allows for deferred function definition as well as insuring that resources that only need to be created once, are created once.</p>
<ul>
<li><strong>Sunday:</strong> <a href="/blog/2008/08/17/a-week-in-javascript-patterns-self-invocation/">Self-invocation</a></li>
<li><strong>Monday:</strong> <a href="/blog/2008/08/18/a-week-in-javascript-patterns-load-time-configuration/">Load Time Configuration</a></li>
<li><strong>Tuesday:</strong> <a href="/blog/2008/08/19/a-week-in-javascript-patterns-the-module/">The Module</a></li>
<li><strong>Wednesday:</strong> Lazy Function Definition</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.lovemikeg.com/blog/2008/08/21/a-week-in-javascript-patterns-lazy-function-definition/feed/</wfw:commentRss>
		</item>
		<item>
		<title>A Week in JavaScript Patterns: The Module</title>
		<link>http://www.lovemikeg.com/blog/2008/08/19/a-week-in-javascript-patterns-the-module/</link>
		<comments>http://www.lovemikeg.com/blog/2008/08/19/a-week-in-javascript-patterns-the-module/#comments</comments>
		<pubDate>Wed, 20 Aug 2008 03:55:34 +0000</pubDate>
		<dc:creator>mikeg</dc:creator>
		
		<category><![CDATA[Code]]></category>

		<category><![CDATA[Design Patterns]]></category>

		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.lovemikeg.com/blog/?p=198</guid>
		<description><![CDATA[The Module is a brilliant design pattern which demonstrates the elegance of the JavaScript language by exploiting closure (one of JavaScript&#8217;s most powerful features) to create private members. The Module makes use of Self-invocation making it useful as an application wrapper.
This pattern was originally discovered and named by Douglas Crockford.
Motivation
By default, there is no natural [...]]]></description>
			<content:encoded><![CDATA[<p>The Module is a brilliant design pattern which demonstrates the elegance of the JavaScript language by exploiting closure (one of JavaScript&#8217;s most powerful features) to create private members. The Module makes use of <a href="/blog/2008/08/17/a-week-in-javascript-patterns-self-invocation/">Self-invocation</a> making it useful as an application wrapper.</p>
<p>This pattern was originally discovered and named by <a href="http://crockford.com">Douglas Crockford</a>.</p>
<h3>Motivation</h3>
<p>By default, there is no natural data hiding functionality in the JavaScript language. As developers push the limits by continually creating more complex applications, the need for private object members becomes increasingly apparent.</p>
<h3>Implementation</h3>
<p>Modules are simply a standard self-invoking function who&#8217;s return value is an object of properties and methods which serve as a public API. In the example below, <samp>foo.bar</samp> is not being set to the value of the anonymous function but rather the object that is returned by the anonymous function.</p>
<pre class="prettyprint">
foo.bar = (function () {
    var baz = function () {};
    var bif = function () {};

    return {
        'thud' : function () {},
        'grunt' : function () {}
    };
})();
</pre>
<p><samp>foo.bar</samp> now has an object as its value which contains two methods: <samp>thud</samp> and <samp>grunt</samp>. <samp>baz</samp> and <samp>bif</samp> are not available publicly, however <samp>thud</samp> and <samp>grunt</samp> still have direct access to them through <a href="http://en.wikipedia.org/wiki/Closure_(computer_science)">closure</a>.</p>
<h4>Understanding Closure</h4>
<p>Closure is a byproduct of <a href="http://en.wikipedia.org/wiki/Functional_Programming">functional programming</a> whereby inner functions have access to local variables defined within an outer function, even after the outer function has returned.</p>
<p>There are several important facts to understand:</p>
<ol>
<li>Functions can contain other functions, just like any other variable. These are <em>inner functions</em>.</li>
<li>Anything not returned by the outer function will not be directly available, however it still exists and is available to any inner functions that shared the same scope.</li>
</ol>
<h3>Conclusion</h3>
<p>With the ability to implement public and private members in an API, developers now have the ability to create robust APIs in JavaScript. This allows developers to create powerful applications while exposing only what is necessary to make it function.</p>
<p>The Module also introduces the concept of closure. This is an  extremely powerful concept of JavaScript which is a result of its functional nature. Future patterns in this series will make heavy use of closure in order to better understand its power and to show the various ways it can be applied.</p>
<h3>Posts in this Series</h3>
<ul>
<li><strong>Sunday:</strong> <a href="/blog/2008/08/17/a-week-in-javascript-patterns-self-invocation/">Self-invocation</a></li>
<li><strong>Monday:</strong> <a href="/blog/2008/08/18/a-week-in-javascript-patterns-load-time-configuration/">Load Time Configuration</a></li>
<li><strong>Tuesday:</strong> The Module</li>
<li><strong>Wednesday:</strong> <a href="/blog/2008/08/21/a-week-in-javascript-patterns-lazy-function-definition/">Lazy Function Definition</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.lovemikeg.com/blog/2008/08/19/a-week-in-javascript-patterns-the-module/feed/</wfw:commentRss>
		</item>
		<item>
		<title>A Week in JavaScript Patterns: Load Time Configuration</title>
		<link>http://www.lovemikeg.com/blog/2008/08/18/a-week-in-javascript-patterns-load-time-configuration/</link>
		<comments>http://www.lovemikeg.com/blog/2008/08/18/a-week-in-javascript-patterns-load-time-configuration/#comments</comments>
		<pubDate>Tue, 19 Aug 2008 02:12:21 +0000</pubDate>
		<dc:creator>mikeg</dc:creator>
		
		<category><![CDATA[Code]]></category>

		<category><![CDATA[Design Patterns]]></category>

		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.lovemikeg.com/blog/?p=175</guid>
		<description><![CDATA[Load time configuration is the process where a JavaScript application configures itself as it is being loaded. This pattern is most commonly found in libraries in which they configure themselves at load time to be optimized for a particular browser.
Load time configuration is also known as load time branching.
Motivation
The primary motivation behind load time configuration [...]]]></description>
			<content:encoded><![CDATA[<p>Load time configuration is the process where a JavaScript application configures itself as it is being loaded. This pattern is most commonly found in libraries in which they configure themselves at load time to be optimized for a particular browser.</p>
<p>Load time configuration is also known as load time branching.</p>
<h3>Motivation</h3>
<p>The primary motivation behind load time configuration is to optimize conditional operations such as generating XMLHttpRequest instances or adding event listeners. Since both operations vary amongst clients, specific conditions must be checked before proceeding. The load time configuration pattern runs once at load time and sets the resulting value so that it doesn&#8217;t need to be checked again.</p>
<h3>Implementation</h3>
<p>The most common technique for implementing load time configuration is by way of a <a href="http://www.lovemikeg.com/blog/2008/08/17/a-week-in-javascript-patterns-self-invocation/">Self-invoking function</a> which returns the correctly configured value.</p>
<p>The example below demonstrates how load time configuration can be used to normalize getting an XMLHttpRequest object.</p>
<pre class="prettyprint">
var getXHR = (function () {
    if (window.XMLHttpRequest) {
        return function () {
            return new XMLHttpRequest;
        }
    }
    else if (window.ActiveXObject) {
        return function () {
            /* Msxml2 and Msxml3 checkes have been omitted
             * for simplicity's sake */
            return new ActiveXObject('Microsoft.XMLHTTP');
        }
    }
})();
</pre>
<p>First, a <samp>getXHR</samp> variable is declared and it&#8217;s value is being assigned by the self-invoking function that follows. Upon execution, a conditional is run which determines the correct method of obtaining an XMLHttpRequest object. When a match is found, a wrapper function is returned and stored as the value for <samp>getXHR</samp> variable.</p>
<h3>Conclusion</h3>
<p>The load time conditional pattern is used to configure a conditional value at load time. The result is a fully optimized value, specific to the the environment in which it is to be used.</p>
<h3>Posts in this Series</h3>
<ul>
<li><strong>Sunday:</strong> <a href="/blog/2008/08/17/a-week-in-javascript-patterns-self-invocation/">Self-invocation</a></li>
<li><strong>Monday:</strong> Load Time Configuration</li>
<li><strong>Tuesday:</strong> <a href="/blog/2008/08/19/a-week-in-javascript-patterns-the-module/">The Module</a></li>
<li><strong>Wednesday:</strong> <a href="/blog/2008/08/21/a-week-in-javascript-patterns-lazy-function-definition/">Lazy Function Definition</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.lovemikeg.com/blog/2008/08/18/a-week-in-javascript-patterns-load-time-configuration/feed/</wfw:commentRss>
		</item>
		<item>
		<title>A Week in JavaScript Patterns: Self-invocation</title>
		<link>http://www.lovemikeg.com/blog/2008/08/17/a-week-in-javascript-patterns-self-invocation/</link>
		<comments>http://www.lovemikeg.com/blog/2008/08/17/a-week-in-javascript-patterns-self-invocation/#comments</comments>
		<pubDate>Sun, 17 Aug 2008 18:20:02 +0000</pubDate>
		<dc:creator>mikeg</dc:creator>
		
		<category><![CDATA[Code]]></category>

		<category><![CDATA[Design Patterns]]></category>

		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.lovemikeg.com/blog/?p=156</guid>
		<description><![CDATA[I would like to begin this series of posts with one of the most useful and commonplace patterns in my code. Arguably, this can be considered a feature of the JavaScript language rather than a design pattern; however, when considering the contexts in which it is applied, I regard it as a pattern.
Self-invocation (also known [...]]]></description>
			<content:encoded><![CDATA[<p>I would like to begin this series of posts with one of the most useful and commonplace patterns in my code. Arguably, this can be considered a feature of the JavaScript language rather than a design pattern; however, when considering the contexts in which it is applied, I regard it as a pattern.</p>
<p>Self-invocation (also known as auto-invocation) is when a function executes immediately upon it&#8217;s definition. This is a core pattern and serves as the foundation for many other patterns of JavaScript development. </p>
<h3>Motivation</h3>
<p>The primary motivation behind self-invoking functions is to create scope. In JavaScript, only functions have scope. Any time variables are defined outside of a function, they are carelessly dumped into the global object. </p>
<h3>Implementation</h3>
<p>A self-invoking function is a standard function, just with a set of parentheses appended to the end.</p>
<pre class="prettyprint">
function () {
    var foo = 'Hello';
    var bar = 'world';
    var baz = [foo, bar];
    alert(baz.join(', '));
}();
</pre>
<p>The above example defines an anonymous function. This creates a literal function, yet since no name is attributed to it, the value is never stored. The trailing parenthesis tell the function to execute, just as if you were calling a named function.</p>
<p>Upon execution, the above function creates three variables, formats them, and alerts them to the user. Once the function terminates, the variables are discarded and the global object remains unchanged.</p>
<h4>Distinguishing from Actual Functions</h4>
<p>Given the oddness of the pattern (and lack of widespread understanding), it is very possible for developers to misinterpret this pattern as an actual function. It it <a href="http://peter.michaux.ca/article/8117">recommended</a> that an extra set of parentheses wrap the function definition as well so to provide a visual clue to the developer that the function isn&#8217;t a normal function. The result would be as follows.</p>
<pre class="prettyprint">
(function () {

    var foo = 'Hello';
    var bar = 'world';
    var baz = [foo, bar];
    alert(baz.join(', '));

})();
</pre>
<h4>Passing Parameters</h4>
<p>In the event where a self-invoking function requires parameters, they can be passed in the same manor that you would a regular function.</p>
<p>The following example applies an &#8220;negative&#8221; class on every input element who&#8217;s numeric value is below 0.</p>
<pre class="prettyprint">
(function (elements) {

    for (var i = 0; i < elements.length; i++) {
        if ((elements[i].value * 1) < 0) {
            elements[i].className = 'negative';
        }
    };

})(document.getElementsByTagName('input'));
</pre>
<h4>Executing in Another Scope</h4>
<p>Even though the function is executing within its own local scope, the <samp>this</samp> keyword will still refer to the global object. </p>
<p>The following example uses the <samp>Function.call()</samp> method to execute a self-invoking function within the scope of the first table element on the page.</p>
<pre class="prettyprint">
(function (elements) {

    for (var i = 5; i < this.rows.length; i++) {
        this.rows[i].className = 'hide';
    }

}).call(document.getElementsByTagName('table')[0]);
</pre>
<h3>Conclusion</h3>
<p>In an effort to protect the global object, all JavaScript applications should be written within a self-invoking function. This will create an application scope in which variables can be created without the fear of them colliding with other applications.</p>
<p>If a global variable is needed, developers must take the extra step by setting them directly within the window object. For example <samp>window.foo = &#8216;bar&#8217;;</samp>. </p>
<p>Self-invocation is a fundamental pattern of professional JavaScript development. Nearly every pattern in this weeks catalog uses it as a base to create scope, closure, or to configure cross-platform objects on-the-fly.</p>
<p>Stay tuned folks. This will be a good week.</p>
<h3>Posts in this Series</h3>
<ul>
<li><strong>Sunday:</strong> Self-invocation</li>
<li><strong>Monday:</strong> <a href="/blog/2008/08/18/a-week-in-javascript-patterns-load-time-configuration/">Load Time Configuration</a></li>
<li><strong>Tuesday:</strong> <a href="/blog/2008/08/19/a-week-in-javascript-patterns-the-module/">The Module</a></li>
<li><strong>Wednesday:</strong> <a href="/blog/2008/08/21/a-week-in-javascript-patterns-lazy-function-definition/">Lazy Function Definition</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.lovemikeg.com/blog/2008/08/17/a-week-in-javascript-patterns-self-invocation/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Ajax for PHP Developers</title>
		<link>http://www.lovemikeg.com/blog/2008/07/26/ajax-for-php-developers/</link>
		<comments>http://www.lovemikeg.com/blog/2008/07/26/ajax-for-php-developers/#comments</comments>
		<pubDate>Sat, 26 Jul 2008 15:45:03 +0000</pubDate>
		<dc:creator>mikeg</dc:creator>
		
		<category><![CDATA[Code]]></category>

		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[PHP]]></category>

		<category><![CDATA[Talks]]></category>

		<guid isPermaLink="false">http://www.lovemikeg.com/blog/?p=114</guid>
		<description><![CDATA[Earlier this week I gave an Ajax presentation for NYPHP. It felt a little strange presenting a JavaScript topic to a bunch of PHP developers, but I made it come back to PHP by demonstrating a the latest Panda PHP package which is only in incubation at the moment. (I&#8217;ll formally announce that in a [...]]]></description>
			<content:encoded><![CDATA[<p>Earlier this week I gave an Ajax presentation for <a href="http://nyphp.org/">NYPHP</a>. It felt a little strange presenting a JavaScript topic to a bunch of PHP developers, but I made it come back to PHP by demonstrating a the latest <a href="http://pandaphp.org/">Panda PHP</a> package which is only in incubation at the moment. (I&#8217;ll formally announce that in a few weeks. Until then, you&#8217;ll have to come to more NYPHP meetings!)</p>
<p>This was my first presentation at NYPHP. It was also the first time I ever went to a formal meeting where we didn&#8217;t just network and drink beer (although there was plenty of that following the presentation).</p>
<p>You can <a href="http://www.slideshare.net/mgirouard/ajax-for-php-developers">view</a> or <a href="http://www.slideshare.net/signup?from_source=http%3A%2F%2Fwww.slideshare.net%2Fmgirouard%2Fajax-for-php-developers&#038;from=download">download</a> the presentation at Slideshare. I also have the <a href="/downloads/talks/Ajax-for-PHP-Developers/code.zip">sample code</a> which I used to demonstrate my concepts.</p>
<p>Enjoy.</p>
<div style="width:425px;text-align:left" id="__ss_524853"><a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" href="http://www.slideshare.net/mgirouard/ajax-for-php-developers?src=embed" title="Ajax for PHP Developers">Ajax for PHP Developers</a><object style="margin:0px" width="425" height="355"><param name="movie" value="http://static.slideshare.net/swf/ssplayer2.swf?doc=ajax-for-php-developers-1216780112990882-8"/><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slideshare.net/swf/ssplayer2.swf?doc=ajax-for-php-developers-1216780112990882-8" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed></object>
<div style="font-size:11px;font-family:tahoma,arial;height:26px;padding-top:2px;">view <a href="http://www.slideshare.net/mgirouard/ajax-for-php-developers?src=embed" title="View Ajax for PHP Developers on SlideShare">presentation</a> (tags: <a style="text-decoration:underline;" href="http://slideshare.net/tag/nyphp">nyphp</a> <a style="text-decoration:underline;" href="http://slideshare.net/tag/php">php</a> <a style="text-decoration:underline;" href="http://slideshare.net/tag/ajax">ajax</a>)</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.lovemikeg.com/blog/2008/07/26/ajax-for-php-developers/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
