<?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>Enterprise jQuery &#187; Multipart Series</title>
	<atom:link href="http://enterprisejquery.com/category/multipart-series/feed/" rel="self" type="application/rss+xml" />
	<link>http://enterprisejquery.com</link>
	<description>Effective, High-Perfomance jQuery for Teams</description>
	<lastBuildDate>Thu, 21 Oct 2010 14:28:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
<atom:link rel="search"
           href="http://enterprisejquery.com/opensearch"
           type="application/opensearchdescription+xml"
           title="Content Search" />		<item>
		<title>How Good C# Habits can Encourage Bad JavaScript Habits:Part 3 &#8211; Function Scope, Hoisting, &amp; Closures</title>
		<link>http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-3/</link>
		<comments>http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-3/#comments</comments>
		<pubDate>Thu, 21 Oct 2010 13:50:53 +0000</pubDate>
		<dc:creator>Elijah Manor</dc:creator>
				<category><![CDATA[Multipart Series]]></category>
		<category><![CDATA[Patterns]]></category>

		<guid isPermaLink="false">http://enterprisejquery.com/?p=706</guid>
		<description><![CDATA[This is the third post in a multi-part series covering common mistakes C# developers tend to make when they first start writing JavaScript. The first post covered the following topics: 1. Having Variables &#38; Functions in Global Scope 2. Not Declaring Arrays &#38; Objects Correctly The second post covered the following topics: 3. Not Understanding [...]
]]></description>
			<content:encoded><![CDATA[<div class="note">
<p>This is the third post in a multi-part series covering common mistakes C# developers tend to make when they first start writing JavaScript.</p>
<p>The <a href="http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1">first post</a> covered the following topics:</p>
<ul>
    <li>1. Having Variables &amp; Functions in Global Scope</li>
    <li>2. Not Declaring Arrays &amp; Objects Correctly</li>
</ul>
<p>The <a href="http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2">second post</a> covered the following topics:</p>
<ul>
    <li>3. Not Understanding False-y Values</li>
    <li>4. Not Testing &amp; Setting Default Values Correctly</li>
    <li>5. Using the Wrong Comparison Operators</li>
    <li>6. Not Using the for&#8230;in Statement Correctly</li>
</ul>
</div>

<h2>Introduction</h2>

<p>This post continues to focus on areas where C# developers tend to make bad JavaScript decisions based on their previous training. The languages are similar enough syntactically that C# developers tend to not invest the time to learn JavaScript&#8217;s differences.</p>

<p>The following post points out several misunderstandings that can get you into some confusing situations.</p>

<p><span id="more-706"></span></p>

<h2>More Bad Practices</h2>

<h3>7. Misunderstanding Scope in JavaScript</h3>

<p>Understanding the different between Block Scope (what C# uses) and Function Scope (what JavaScript uses) is one of the most important things you should know when moving from C# to JavaScript. If you don&#8217;t understand this concept then things can get confusing real quick.</p>

<p>In C#, if you declare a variable inside of a set of brackets then the lifetime of the variable only lives inside that scope. However, in JavaScript, the variables you declare inside a function are available to any other code within that function scope.</p>

<p>Let&#8217;s look at the following code and see what concepts we can learn.</p>

<pre class="brush: jscript;">
// Code written thinking that JavaScript has block scope
function eat() {
    var food = &quot;bacon&quot;,
        isHungry = true;

    if ( isHungry ) {
        //A C# developer might think that timeToWait is
        //only accessible from within this if statement,
        //but that is not the case
        var timeToWait = 10;

        console.log( &quot;Waiting &quot; + timeToWait + &quot; minutes&quot; );

        chew();
    }

    function chew() {
        var bodyPart = &quot;mouth&quot;;

        //The chew function also has access to the
        //timeToWait variable because it is part of the
        //eat function's scope
        console.log( &quot;After waiting &quot; + timeToWait +
            &quot; minutes, &quot; + &quot;I am eating &quot; + food +
            &quot; with my &quot; + bodyPart );
    }
}

eat();
//Waiting 10 minutes
//After waiting 10 minutes, I am eating bacon with my mouth
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/E2Rmw/3/">jsFiddle</a>.</p>

<p>A C# developer might look at the above code and think that the <code>timeToWait</code> variable is only accessible by the if statement, but that isn&#8217;t true. The <code>timeToWait</code> variable is accessible anywhere within the eat function. So, that means the chew method can use the <code>timeToWait</code> variable as well.</p>

<div class="note">
<p>If the above code snippet is confusing to you, it is probably because of something called variable and function hoisting. We will discuss these concepts in the next section, which should help clear up some of the confusion that you may have.</p></div>

<p>Instead of declaring your variables throughout the eat function, they should have all been declared at the top. By doing so, it would be more obvious that the scope is on the function and not the block level as a C# developer might expect. I have rearranged the variable declaration to make more sense below.</p>

<pre class="brush: jscript;">
// Code written understanding JavaScript has function scope
function eat() {
    //Declare all your variables at the top so that it is
    //obvious you are using function scope and not block
    //scope
    var food = &quot;bacon&quot;,
        isHungry = true,
        timeToWait, bodyPart;

    if ( isHungry ) {
        timeToWait = 10;

        console.log( &quot;Waiting &quot; + timeToWait + &quot; minutes&quot; );

        chew();
    }

    function chew() {
        bodyPart = &quot;mouth&quot;;

        console.log( &quot;After waiting &quot; + timeToWait +
            &quot; minutes. &quot; + &quot;I am eating &quot; + food +
            &quot; with my &quot; + bodyPart );
    }
}

eat();
//Waiting 10 minutes
//After waiting 10 minutes, I am eating bacon with my mouth
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/qANjt/3/">jsFiddle</a>.</p>

<h4>Best Practice</h4>

<p>It is considered best practice to declare all of your variables at the top of your function. By declaring your variables at the top of your function, you are sending a message to yourself and anyone else that those variables are available to anything inside of the function.</p>

<p>It turns out there is an even more compelling reason to declare your variables at the top of your function.</p>

<h3>8. Not Knowing Variable and Function Hoisting</h3>

<p>As we examined in the above section, JavaScript uses Function Scope instead of Block Scope. How exactly does that work? Behind the scenes JavaScript does something called variable and function hoisting.</p>

<h4>Variable Hoisting</h4>

<p>In JavaScript all the variables inside of a function share the same scope. Inside of a function, JavaScript first looks for all the variable declarations, hoists their declarations to the top of the function, and then initializes them to undefined. Their assignments still remain on the same line where you originally declared them. This is known as &#8216;variable hoisting&#8217;.</p>

<p>For example let&#8217;s say that we wrote the following piece of JavaScript code</p>

<pre class="brush: jscript;">
//Code You Might Write
function sayHello( firstName, middleName, lastName ) {
    var fullName = firstName + &quot; &quot; + middleName + &quot; &quot; +
        lastName;

    if ( fullName === &quot;Carlos Rey Norris&quot; ) {
        var nickName = &quot;Chuck&quot;;

        console.log( &quot;Hello &quot; + nickName + &quot; &quot; +
            fullName.split(&quot; &quot;)[2] );
    }
}

sayHello( &quot;Carlos&quot;, &quot;Rey&quot;, &quot;Norris&quot; ); //Hello Chuck Norris
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/UZyue/3/">jsFiddle</a>.</p>

<p>Behind the scenes JavaScript takes the <code>fullName</code> and <code>nickName</code> variables and declares them all at the top of the function. Their assignments remain in the same place, but their declaration location changed.</p>

<pre class="brush: jscript;">
//How JavaScript Interprets It
function sayHello( firstName, middleName, lastName ) {
    //Hoists all the variable declarations to the top
    //of the function and sets to undefined
    var fullName = undefined,
        nickName = undefined;

    //fullName assignment remains in original position
    fullName = firstName + &quot; &quot; + middleName + &quot; &quot; + lastName;

    if ( fullName === &quot;Carlos Rey Norris&quot; ) {
        //nickName assigned remains in original position
        nickName = &quot;Chuck&quot;;

        console.log( &quot;Hello &quot; + nickName + &quot; &quot; +
            fullName.split(&quot; &quot;)[2] );
    }
}

sayHello( &quot;Carlos&quot;, &quot;Rey&quot;, &quot;Norris&quot; ); //Hello Chuck Norris
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/Fg4QV/3/">jsFiddle</a>.</p>

<h4>Where Things Can Get Confusing: Part 1</h4>

<p>Not knowing this can lead you into some pretty confusing situations. For example, take a look at the following example.</p>

<pre class="brush: jscript;">
//Where You Can Get Into Trouble
for ( var i = 0; i &lt; 10; ++i ) {
    for ( var i = 0; i &lt; 5; ++i ) {
        console.log( &quot;Hello&quot; );
    }
}
</pre>

<p>Do you see what is wrong in the above code? The intent of the developer was to print out &#8220;Hello&#8221; 50 times, but the result is an infinite loop that prints out &#8220;Hello&#8221; continuously! A C# developer might think that each <code>i</code> variable is in it&#8217;s own scope, but not in JavaScript. JavaScript hoisted the <code>i</code> variable to the top of the function and both loops are updating the same variable. The effect is that the inner loop is never letting the outter loop&#8217;s <code>i</code> variable reach 10, which is why the code never exits the loop.</p>

<h4>Where Things Can Get Confusing: Part 2</h4>

<p>Here is another example of where you might get confused about scope. The following code declares <code>someVariable</code> outside of the function and then the <code>someVariable</code> variable is written to the console immediately inside the function. At first glance, that seems like it should work, but in the following example it does not!</p>

<pre class="brush: jscript;">
//Where You Can Get Into Trouble

console.log( someVariable ); //undefined
var someVariable = 42; //Global variable
console.log( someVariable ); // 42

function doSomething() {
    console.log( someVariable ); // undefined
    //Why is someVariable undefined?
    //Developer expected to see 42 from global variable

    someVariable = 1
    console.log( someVariable ); // 1

    console.log( window.someVariable ); // 42
    //Why is window.someVariable 42?
    //Developer thought he just set global variable to 1

    if ( false ) {
        var someVariable = 0;
    }
}

doSomething();

console.log( someVariable ); // 42
//Why is someVariable is 42?
//Developer expected to see 1 from global variable
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/Ty8dN/17/">jsFiddle</a>.</p>

<p>Let&#8217;s rewrite the same code above, but this time as JavaScript would interpret it with variable hoisting.</p>

<pre class="brush: jscript;">
//How JavaScript Interprets It

var someVariable = undefined;
console.log( someVariable ); //undefined
someVariable = 42; //Global variable
console.log( someVariable ); // 42

function doSomething() {
    //Because of variable hoisting var is
    //moved to the top of the function and set to undefined
    var someVariable = undefined;
    console.log( someVariable ); // undefined

    someVariable = 1
    console.log( someVariable ); // 1
    //This above line of code didn't set the global
    //instance, but the local one that was hoisted

    console.log( window.someVariable ); // 42

    if ( false ) {
        someVariable = 0;
    }
}

doSomething();

console.log( someVariable ); // 42
//Because of variable hoisting in
//doSomething the code inside never updated
//the global variable
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/UQ9TL/1/">jsFiddle</a>.</p>

<p>When you understand how hoisting works it is easier to understand why the <code>someVariable</code> variable was undefined immediately inside the function. Since there was a <code>var someVariable = 0;</code> inside the if statement, that variable got hoisted to the top of the function. So, instead of &#8220;someVariable&#8221; referencing the global instance, it is referencing the local <code>someVariable</code> variable declared in the function scope.</p>

<p>As you can tell, if you don&#8217;t have a good understanding on how function scope works, then you can get into some trouble real fast.</p>

<h4>And Then There Was Function Hoisting</h4>

<p>Now that you have a good grasp on variable hoisting, let&#8217;s change our focus somewhat to function statements and function expressions. The hoisting rules for functions aren&#8217;t exactly the same as they are for variables. First, we need to understand the difference between a function statement and a function expression. The easiest way to tell them apart is, if it starts with the <code>function</code> keyword, then it is a function statement. See the following examples comparing the two function declarations.</p>

<pre class="brush: jscript;">
//Example with various function declarations 

try {
    sayHello(); //Error because not defined
} catch (e) {
    //Property 'sayHello' of object [object DOMWindow]
    //is not a function
    console.log(e.message);
}
sayGoodbye(); //Goodbye

//Function Expression
var sayHello = function() {
    console.log(&quot;Hello&quot;);
};

sayHello(); //Hello
sayGoodbye(); //Goodbye

//Function Statement
function sayGoodbye() {
    console.log(&quot;Goodbye&quot;);
}

sayHello(); //Hello
sayGoodbye(); //Goodbye
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/9F9da/5/">jsFiddle</a>.</p>

<p>The above function statement is transformed behind the scenes into a function expression and then both the variable and the assignment are hoisted to the top of the function scope.</p>

<p>For example, let me rewrite the above code snippet as JavaScript would interpret it.</p>

<pre class="brush: jscript;">
//How JavaScript Interprets It

var sayHello = undefined,
    sayGoodbye = undefined;

//Function Statement was converted to a
//function expression and both the variable
//and assignment were hoisted to the top of
//the function
sayGoodbye = function() {
    console.log(&quot;Goodbye&quot;);
};

try {
    sayHello(); //error
} catch(e) {
    //Property 'sayHello' of object [object DOMWindow]
    //is not a function
    console.log(e.message);
}
sayGoodbye(); //Goodbye

//The declaration of the Function Expression was
//hoisted to the top of the function, but the
//assignment stayed in the original location
sayHello = function() {
    console.log(&quot;Hello&quot;);
};

sayHello(); //Hello
sayGoodbye(); //Goodbye

//sayGoodbye Function statement was here, but got
//completely hoisted to the top of the function

sayHello(); //Hello
sayGoodbye(); //Goodbye
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/BSuWQ/5/">jsFiddle</a>.</p>

<p>As you can see from the above example, function expressions follow the same rules as variable hoisting, but function statements vary slightly. A function statement is first converted to a function expression and instead of just hoisting the declaration, it hoists both the declaration and the assignment of the function as well.</p>

<h4>Best Practice</h4>

<p>Since JavaScript uses Function Scope and hoists it&#8217;s variable declarations, it is considered best practice to declare all of your variables at the top of your function.</p>

<h3>9. Not Using Closures Correctly Or At All</h3>

<p>Using a closure is a way to keep variables alive after a function has returned. The Mozilla Developer Network has a <a href="https://developer.mozilla.org/en/JavaScript/Guide/Closures">great page explaining closures</a>. In it they provide a core definition:</p>

<blockquote>
  <p>&#8220;A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created.&#8221;</p>
</blockquote>

<p>A closure can be very helpful when needing to enclose certain variables to a particular scope or when we need to maintain state inside an object. We will examine a common code scenario and examine what is going on and how we might be able to fix it using a closure.</p>

<h4>Looping Without A Closure</h4>

<p>The intent of the following code snippet is to add an event handler to 10 different DOM elements and each one should alert it&#8217;s ID attribute (e.g. &#8220;You&#8217;ve clicked 3&#8243;). You should know that if this was your actual intent, then there is a much easier way to do this, but for academic reasons let&#8217;s stick with this implementation.</p>

<pre class="brush: jscript;">
//broken
var unorderedList = $( &quot;ul&quot; );
for (var i = 0; i &lt; 10; i++) {
    $(&quot;&lt;li /&gt;&quot;, {
        id: i,
        text: &quot;Link &quot; + i,
        click: function() {
            console.log(&quot;You've clicked &quot; + i);
        }
    }).appendTo( unorderedList );
}
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/cQ7Ug/4/">jsFiddle</a>.</p>

<p>The output of the above code may not be what you first expect. The result of every click handler will be &#8220;You&#8217;ve clicked 9&#8243; because the value of <code>i</code> at the point the event handler was fired is &#8220;9&#8243;. What the developer really wanted is for the value of <code>i</code> to be displayed at the point in time the event handler was defined.</p>

<h4>Looping With A Closure: Part 1</h4>

<p>In order to fix the above bug we can introduce a closure.</p>

<pre class="brush: jscript;">
//working
var unorderedList = $( &quot;ul&quot; ), i;

for (i = 0; i &lt; 10; i++) {
    $(&quot;&lt;li /&gt;&quot;, {
        id: i,
        text: &quot;Link &quot; + i,
        click: function(index) {
            return function() {
                console.log(&quot;You've clicked &quot; + index);
            }
        }(i)
    }).appendTo( unorderedList );
}
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/XS7BE/2/">jsFiddle</a>.</p>

<p>One way to fix the above code is to utilize a self-executing anonymous function. That is a fancy term that means we are going to create a nameless function and then immediately call it. The value of this technique is that the scope of the variable stays within the function. So, first we will surround the event handler content in a function and then immediately call the function and pass in the value of <code>i</code>. By doing that, when the event handler is triggered it will contain the value of <code>i</code> that existed when the event handler was defined.</p>

<h4>Looping With A Closure: Part 2</h4>

<p>If the above syntax is new to you, then you might consider the following code snippet, which is essentially the same thing, but split out a little more. Instead of using an anonymous function, we are defining a named function and passing the value of <code>i</code> into it so the scope will remain in the function.</p>

<pre class="brush: jscript;">
var unorderedList = $( &quot;ul&quot; ), i;

for (i = 0; i &lt; 10; i++) {
    $(&quot;&lt;li /&gt;&quot;, {
        id: i,
        text: &quot;Link &quot; + i,
        click: clickEventHandler(i)
    }).appendTo( unorderedList );
}

function clickEventHandler( index ) {
    return function() {
        console.log(&quot;You've clicked &quot; + index);
    }
}
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/A6tTF/3/">jsFiddle</a>.</p>

<h4>Best Practice</h4>

<p>As seen in the above examples, a closure can be very helpful when trying to persist certain variable states. There are actually several other really good uses for closures as well. A pattern that I use frequently is called the <a href="http://www.klauskomenda.com/code/javascript-programming-patterns/#revealing">Revealing Module Pattern</a>, which uses the concept of closures to simulate private methods and properties as you might expect from C#.</p>

<p>For more examples of when to use closures appropriately in your code there is a great post by <a href="http://twitter.com/kangax">Juriy Zaytsev</a> on Script Junkie entitled <a href="http://msdn.microsoft.com/en-us/scriptjunkie/ff696765.aspx">Use Cases for JavaScript Closures</a></p>

<h2>So What Now?</h2>

<h3>Tools To Help You</h3>

<p>Many of the above issues we&#8217;ve addressed can be found during development by running your code through <a href="http://www.jsonlint.com/">JSLint</a>, which is a JavaScript code analyzer that Douglas Crockford developed. It takes many of the concepts from his experience and boils them down into a set of rules you can execute against your code.</p>

<p>You might also consider running your code through another tools called <a href="http://doctorjs.org/">DoctorJS</a>. This tool builds on the concepts taught by Douglas Crockford and extends them somewhat with their own best practices.</p>

<p>A combination of these two tools should help pinpoint some obvious practices that you should change in your code. Passing these tools does not mean you have good code, but it can help you identify areas that need some attention.</p>

<h3>Sources for Additional Learning</h3>

<p>As you&#8217;ve probably noticed I&#8217;ve mentioned Douglas Crockford a lot in this article. A lot of his work identifies areas where classical languages such as C# vary from JavaScript. He has a great book entitled <a href="http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742">JavaScript: The Good Parts</a> that I highly suggest you reading. You can also check out his phenomenal <a href="http://yuiblog.com/crockford/">Crockford on JavaScript</a> video series on Yahoo! that covers much of the content of the previously mentioned book.</p>

<p>In addition, the JavaScript articles on the Microsoft <a href="http://msdn.microsoft.com/en-us/scriptjunkie/default.aspx">Script Junkie</a> website are top notch. I highly recommend checking them out. The authors on the site are top notch experts from the field. Here is a small taste of some of the great article you can find:</p>

<ul>
<li><a href="http://msdn.microsoft.com/en-us/scriptjunkie/ff852808.aspx">Prototypes and Inheritance in JavaScript</a> by <a href="http://twitter.com/odetocode">Scott Allen</a></li>
<li><a href="http://msdn.microsoft.com/en-us/scriptjunkie/ff696759.aspx">Style in jQuery Plugins and Why it Matters</a> by <a href="http://twitter.com/cowboy">Ben Alman</a></li>
<li><a href="http://msdn.microsoft.com/en-us/scriptjunkie/ff698349.aspx">Intro to Error Handling in Ajax Apps</a> by Me</li>
<li><a href="http://msdn.microsoft.com/en-us/scriptjunkie/ff696765.aspx">Use Cases for JavaScript Closures</a> by <a href="http://twitter.com/kangax/">Juriy Zaytsev</a></li>
<li><a href="http://msdn.microsoft.com/en-us/scriptjunkie/ff715319.aspx">Introduction to the Reactive Extensions to JavaScript</a> by <a href="http://twitter.com/mattpodwysocki">Matt Podwysocki</a></li>
<li>Many more&#8230;</li>
</ul>

<p>There is also a great blog post series by <a href="">Julian Bucknall</a> entitled <a href="http://blog.boyet.com/blog/javascriptlessons/">JavaScript for C# Programmers</a>. The posts were from some time ago, but their content is still timely and very much top notch.</p>

<h2>Conclusion</h2>

<p>The intent of these articles was to shed some light on practices that a C# already does that might become an immediate issue in JavaScript development.</p>

<p>In addition to the bad practices that I&#8217;ve mentioned in this series, there are many more things that a C# developer should know. JavaScript is a very powerful language and has unfortunately received a bad wrap primarily because of the painful nature of the DOM.</p>

<p>JavaScript is similar enough to C# that you feel comfortable, but different enough that is worth diving into it deeper. You can actually do some pretty cool things that you can&#8217;t do in C#. I hope you find these tips helpful.</p>
]]></content:encoded>
			<wfw:commentRss>http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-3/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>How Good C# Habits can Encourage Bad JavaScript Habits:Part 2 &#8211; False-y, Testing and Default Values, Comparisons, and Looping</title>
		<link>http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2/</link>
		<comments>http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2/#comments</comments>
		<pubDate>Wed, 13 Oct 2010 09:51:21 +0000</pubDate>
		<dc:creator>Elijah Manor</dc:creator>
				<category><![CDATA[Multipart Series]]></category>
		<category><![CDATA[Patterns]]></category>

		<guid isPermaLink="false">http://enterprisejquery.com/?p=687</guid>
		<description><![CDATA[This is the second post in a multi-part series covering common mistakes C# developers tend to make when they first start writing JavaScript. The first post covered the following topics: 1. Having Variables &#38; Functions in Global Scope 2. Not Declaring Arrays &#38; Objects Correctly Introduction This post continues to focus on areas where C# [...]
]]></description>
			<content:encoded><![CDATA[<div class="note">
<p>This is the second post in a multi-part series covering common mistakes C# developers tend to make when they first start writing JavaScript.</p> 
<p>The <a href="http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1">first post</a> covered the following topics:</p>
<ul>
    <li>1. Having Variables &amp; Functions in Global Scope</li>
    <li>2. Not Declaring Arrays &amp; Objects Correctly</li>
</ul>
</div>

<h2>Introduction</h2>

<p>This post continues to focus on areas where C# developers tend to make poor decisions when writing JavaScript based on their previous training. The languages are syntactically similar enough that C# developers tend to not invest the time to learn JavaScript&#8217;s differences.</p>

<p>The following post points out several misunderstandings that can get you into some confusing situations.</p>

<p><span id="more-687"></span></p>

<h2>More Bad Practices</h2>

<h3>3. Not Understanding False-y Values</h3>

<p>Unlike C# there are many values that JavaScript has that act false-y. Inside an if statement truth-y values will proceed into the then branch and false-y values will drop into the else branch. It is important to understand these special false-y values not only when writing your code, but when trying to understand other people&#8217;s code. </p>

<p>The False-y values are:</p>

<pre class="brush: jscript;">
false
null
undefined
&quot;&quot; (empty string)
0
NaN (not a number)
</pre>

<p>All other values that aren&#8217;t listed in the above list will be considered truth-y (including all objects, the strings &#8220;0&#8243;, &#8220;false&#8221;, and many other strange combinations).</p>

<h4>Best Practice</h4>

<p>When it comes to understanding the outcome of a logical statement, you should know the false-y values in JavaScript. Since these rules are considerably different than C#, you should take the time to understand them.</p>

<p>We will examine the implications of knowing these false-y values a little further in the next few sections.</p>

<h3>4. Not Testing &amp; Setting Default Values Correctly</h3>

<p>You can easily spot a C# developer if you see them checking for null inside of an if statement or when setting a default value.</p>

<h4>Checking for Null</h4>

<p>It is common and considered a best practice in C# to check for null before using a variable. If you don&#8217;t, then you might fall victim to the dreaded &#8220;Object reference not set to an instance of an object&#8221; exception. Also, when dealing with strings you&#8217;ll also want to test if it is empty or not. The following code snippet is a typical way to do this in C#.
<pre class="brush: jscript;">
// C# example. Don't do this in JavaScript
if ( someString != null &amp;&amp;
    someString.length &gt; 0 ) {
    //Do something here...
}
</pre></p>

<p>In fact, the above code snippet is such a common practice that there is a special <code>IsNullOrEmpty</code> method in the .NET framework to help simplify this case.</p>

<pre class="brush: jscript;">
// C# code to simplify checking for null and empty string
if ( !string.IsNullOrEmpty(someString) ) {
    //Do something here...
}
</pre>

<p>As it turns out, when considering the JavaScript false-y values, you can shorten all this logic to the following code snippet. The following code snippets checks to see if the variable is not undefined, not null, and is not empty.</p>

<pre class="brush: jscript;">
// Simplified JavaScript syntax to check for
// undefined, null, &amp; empty string values
if ( someString ) {
    //Do something here...
}
</pre>

<p>As a side note, the above <code>someString</code> variable is more likely to be undefined than it is null due to variable hoisting, but thanks to false-y values that is being checked.</p>

<h4>Setting A Default Value</h4>

<p>Another common scenario you&#8217;ll run into is setting a default value to a variable. In C#, you might be be tempted to write some code like the following.</p>

<pre class="brush: jscript;">
// C# example. Don't do this in JavaScript
if ( someString == null ) {
   someString = &quot;default Value&quot;;
}

// Slightly better, but don't do this either
someString = someString ? someString : &quot;default value&quot;;
</pre>

<p>Instead, there is a much simpler way to perform this in JavaScript that uses the logic or operator.</p>

<pre class="brush: jscript;">
// JavaScript syntax to set a default value
someString = someString || &quot;default value&quot;;
</pre>

<h4>Best Practice</h4>

<p>Based on the false-y rules we learned earlier, if we want to check if a variable is undefined, not null, and has a value then all we need to do is check the object itself.</p>

<h3>5. Using the Wrong Comparison Operators</h3>

<p>Knowing that JavaScript is loosely typed and having the False-y values fresh in our mind from the previous section, let&#8217;s focus now on common mistakes when using the comparison operator.</p>

<p>Coming from C# you will intuitively use the <code>==</code> and <code>!=</code> in your if statements, however, this may yield some results that you didn&#8217;t expect.</p>

<h4>Problems When Using == or != Comparison Operators</h4>

<p>When using the <code>==</code> and <code>!=</code> comparison operators, JavaScript tries to help you by coercing the two values into the same type so that it can compare them. This sounds like a good idea, but in the end it can lead to some very confusing results. Check out the following for some of these unexpected results.</p>

<pre class="brush: jscript;">
// Unexpected Comparisons using the == Operator
0          ==  ''        //true
0          ==  '0'       //true
false      ==  '0'       //true
null       ==  undefined //true
' \t\r\n ' ==  0         //true
</pre>

<h3>You Should Use the <code>===</code> or <code>!==</code> Instead</h3>

<p>A better way to compare is to use the <code>===</code> and <code>!==</code> operators (also known at the identify operators), which are much more rigorous. They will not only check the value, but also check the type as well. The results of these comparisons are probably more what you would expect in a strongly typed language. The following code uses the same comparison as the above example, but uses the identify operator instead.</p>

<pre class="brush: jscript;">
// Expected Comparisons using the === Operator
0          === ''        //false
0          === '0'       //false
false      === '0'       //false
null       === undefined //false
' \t\r\n ' === 0         //false
</pre>

<h4>Best Practice</h4>

<p>When you are comparing two values in JavaScript you should use the Identify Comparison Operators (<code>===</code> &amp; <code>!==</code>).</p>

<h3>6. Not Using the for…in Statement Correctly</h3>

<p>For those of you who regularly write C#, you probably don&#8217;t use the classic for loop much, but use the <code>for…in</code> loop instead. If you aren&#8217;t careful this can byte you in several different ways.</p>

<h4>Using the for…in Statement on Arrays</h4>

<p>You may see the <code>for…in</code> statement used to iterate over arrays, but don&#8217;t! You can get into some weird issues. You should instead use the <code>for</code> statement when looping over arrays.</p>

<p>The <code>for…in</code> statement does not guarantee the order of the items that are going to be retrieved, plus you can get into some interesting problems.</p>

<p>In the following example we are creating an array and then setting the 5th index with a value of &#8220;test&#8221;. Since we have an item at the 5th index, the array is marked as having a length of 6 items. So far, there shouldn&#8217;t be any surprises here.</p>

<pre class="brush: jscript;">
var myArray = [], name;
myArray[5] = &quot;test&quot;;
console.log( myArray.length ); //6
</pre>

<p>However, if you used the <code>for..in</code> statement on this array, you would only see the one item that you inserted in the array, which is probably not what you intended. If this is what you intended, then you should probably not be using an array and should be using an object instead.</p>

<pre class="brush: jscript;">
var myArray = [], name;
myArray[5] = &quot;test&quot;;
console.log( myArray.length ); //6

for ( name in myArray ) {
    console.log( name, myArray[name] );
    //Outputs...
    //   5, test
}
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/x23Jh/1/">jsFiddle</a>.</p>

<p>You should use the standard <code>for</code> loop when iterating over an array. The following example does loop over the entire range of indexes, although most of them are undefined since we didn&#8217;t set their values.</p>

<pre class="brush: jscript;">
var myArray = [], name;
myArray[5] = &quot;test&quot;;
console.log( myArray.length ); //6

for ( var i = 0, length = myArray.length; i &lt; length; i++ ) {
    console.log( i, myArray[i] );
    //Outputs...
    //   0, undefined
    //   1, undefined
    //   2, undefined
    //   3, undefined
    //   4, undefined
    //   5, test
}
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/J7SQC/">jsFiddle</a>.</p>

<p>If you are not convinced, there is another problem that you can run into when using the <code>for…in</code> statement on an array. Now just suppose that you or some other library changed the prototype of the Array object? If someone where to add a property to the Array.prototype it would also show up as one of the keys in the <code>for…in</code>.</p>

<pre class="brush: jscript;">
var myArray = [], name;
myArray[5] = &quot;test&quot;;
console.log( myArray.length ); //6

Array.prototype.someVariable = &quot;Where did this come from?&quot;;
for ( name in myArray ) {
    console.log( name, myArray[name] );
    //Outputs...
    //   5, test
    //   someVariable, Where did this come from?
}
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/Vgx7E/">jsFiddle</a>.</p>

<p>This actually brings up our next subtopic about using the <code>for…in</code> statement correctly when using an object.</p>

<h4>Using the For…In Statement Incorrectly with Objects</h4>

<p>As we discussed briefly in the above section, hopefully you are only using the <code>for…in</code> statement with objects and not arrays. You might have seen the <code>for…in</code> used like the following</p>

<pre class="brush: jscript;">
for ( var name in object ) {
    //Your code here
}
</pre>

<p>That seems harmless, right? And in many cases it does exactly what you want it to. As it turns out, you should be careful using the above syntax. The <code>for…in</code> statement will actually iterate through all the properties of the object and also the properties that are inherited from the prototype! Since you probably don&#8217;t want to iterate over your inherited prototype properties, you should check the object you are enumerating to see if it contains the property before proceeding.</p>

<p>Your modified code snippet should look something like the following instead.</p>

<pre class="brush: jscript;">
/* Check if object has property before
iterating, because functions inherited
from prototype are also included */
for ( var name in object ) {
   if ( object.hasOwnProperty(name) ) {
      //Your code here
   }
}
</pre>

<p>The following code snippet shows an example of when the <code>for…in</code> statement might show some undesired results.</p>

<pre class="brush: jscript;">
var Person = function( firstName, lastName ) {
  this.firstName = firstName;
  this.lastName = lastName;
  return this;
};

Person.prototype = {
  isMarried : false,
  hasKids: false
};

var john = new Person( &quot;John&quot;, &quot;Smith&quot; ),
  linda = new Person( &quot;Linda&quot;, &quot;Davis&quot; ),
  name;

john.isMarried = true;

console.log( &quot;Not Checking hasOwnProperty&quot; );
for ( name in john ) {
  console.log( name + &quot;: &quot; + john[name] );
  //Outputs
  //  firstName: John
  //  lastName: Smith
  //  isMarried: true
  //  hasKids: false
}

console.log( &quot;Checking hasOwnProperty&quot; );
for ( name in linda ) {
  if ( linda.hasOwnProperty(name) ) {
    console.log( name + &quot;: &quot; + linda[name] );
    //Outputs
    //  firstName: Linda
    //  lastName: Davis
  }
}
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/AVVaH/">jsFiddle</a>.</p>

<p>In the above code we created two Person objects and set it&#8217;s prototype to include two new properties (&#8220;isMarried&#8221; and &#8220;hasKids&#8221;). We then loop over the properties of the &#8220;john&#8221; person, you will see that not only are his firstName and lastName displayed, but also the inherited &#8220;isMarried&#8221; and &#8220;hasKids&#8221; prototype values! In contrast, by checking <code>.hasOwnProperty()</code> when looping over linda&#8217;s properties, we only see that her immediate properties are displayed, instead of displaying her inherited properties as well.</p>

<h4>Best Practice</h4>

<p>The take aways for this point are:
* Use the <code>for</code> statement for arrays
* Use the <code>for…in</code> statement when iterating over objects and check the <code>hasOwnProperty</code> method</p>

<h2>Conclusion</h2>

<p>This article has covered some of the common issues you might address coming from C# to JavaScript. I have committed just about everyone of the above Bad Practices myself when I starting to code in JavaScript heavily.</p>

<p>With the recent serge of jQuery hitting the market and other great JavaScript libraries, it is important that we as developers understand the language instead of just thinking that our previous language knowledge will get us by.</p>

<p>This article only covers some of the things you should know. The next post in the series will be published next week. In the meantime please feel free to add comments of any other gotchas that you&#8217;ve experience coming from a C# background. I would love to hear about it.</p>
]]></content:encoded>
			<wfw:commentRss>http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>How Good C# Habits can Encourage Bad JavaScript Habits:Part 1</title>
		<link>http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/</link>
		<comments>http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/#comments</comments>
		<pubDate>Thu, 07 Oct 2010 18:06:15 +0000</pubDate>
		<dc:creator>Elijah Manor</dc:creator>
				<category><![CDATA[Multipart Series]]></category>
		<category><![CDATA[Patterns]]></category>

		<guid isPermaLink="false">http://enterprisejquery.com/?p=623</guid>
		<description><![CDATA[This is the first post in a multi-part series covering common mistakes C# developers tend to make when they first start writing JavaScript. Introduction Many people come to jQuery and believe that their knowledge of a previous classical language (C#, Java, etc) will help them be successful at client-side scripting. You can use your classical [...]
]]></description>
			<content:encoded><![CDATA[<div class="note">This is the first post in a multi-part series covering common mistakes C# developers tend to make when they first start writing JavaScript.</div>

<h2>Introduction</h2>

<p>Many people come to jQuery and believe that their knowledge of a previous classical language (C#, Java, etc) will help them be successful at client-side scripting. You can use your classical language skills to accomplish a large amount of functionality with jQuery. However, the more client-side code you write you will find yourself uncovering strange bugs because you didn&#8217;t take adequate time to learn JavaScript properly. </p>

<blockquote>
  <p>&#8220;&#8230;it turns out that if you have absolutely no idea what you’re doing in the language you can still generally make things work.&#8221; &#8211;Douglas Crockford, Yahoo!&#8217;s JavaScript Architect, <a href="http://developer.yahoo.com/yui/theater/video.php?v=crockonjs-2">Douglas on JavaScript -- Chapter 2: And Then There Was JavaScript</a> </p>
</blockquote>

<p>This article is targeted for developers that use jQuery but haven’t invested the time necessary to learn JavaScript. The intent is to help you avoid some common mistakes when moving from a classical language (Java, C#, etc) to JavaScript.</p>

<p>jQuery is a library that is written in JavaScript. It is important to remember that you will always be writing in JavaScript when using jQuery. It is inevitable that you will run into native JavaScript concepts that are foreign to the classical language proficient developer. Taking the time now to be proficient in JavaScript will increase your client-side code quality, efficiency, and decrease code maintenance. </p>

<p><span id="more-623"></span></p>

<h2>Bad Practices</h2>

<h3>1. Having Variables &#038; Functions in Global Scope</h3>

<p>A best practice in C# is to limit the use of global variables. This doesn&#8217;t necessarily translate into a bad practice in JavaScript, but most C# developers are not aware of how easily it is to pollute the global namespace with needless variables and functions.</p>

<p>One way you can pollute the global namespace is to not declare your variables. In JavaScript, if you don&#8217;t declare your variables then they become globally available to the rest of the program, which is probably not what you wanted and generally a bad idea.</p>

<p>Coming from a C# background, you are most likely used to the concept of namespacing your classes so they won&#8217;t clash with other libraries. In the same way you should be mindful to not declare variables or functions in the global namespace to prevent clashing with other libraries, browser extensions, and also your own code. </p>

<h4>Bad Practice</h4>

<p>The following code shows some bad examples of how to declare variables and functions.</p>

<pre class="brush: jscript;">
var iAmGlobal = &quot;Keep these to a minimum&quot;;

iAmGlobalToo = &quot;Bad&quot;;

function oldSchoolWay() {
    //Placed in global scope when executed
    iAmGlobalNooo = &quot;Really Bad&quot;; 

    console.log( &quot;Bad oldSchoolWay Function&quot; );
}

//Bad way to prevent namespace clashing
function namespace_oldSchoolWay() {
    console.log( &quot;Worse oldSchoolWay Function&quot; );
}

//Functions 
window.oldSchoolWay();
window.namespace_oldSchoolWay();

//Global variables are available off window object
console.log( window.iAmGlobal );
console.log( window.iAmGlobalToo );
console.log( window.iAmGlobalNooo );
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/teW4J/4/">jsFiddle</a>.</p>

<p>In the above code snippet you&#8217;ll see that the <code>iAmGlobal</code>, <code>iAmGlobalToo</code>, and <code>iAmGlobalNooo</code> are all global variables. You would expect <code>iAmGlobal</code> and probably <code>iAmGlobalToo</code> to be global variables, but the variable inside the <code>oldSchoolWay</code> function is also global because it was never declared! The best way to stay out of this trouble is to be disciplined and declare all of your variables and not let JavaScript do it for you.</p>

<p>Klaus Komenda actually refers to the function statement as the Old School Way of function declaration. I&#8217;ve even seen C# developers trying to prefix their function names (as shown above by namespace_oldSchoolWay) to minimize collisions with other libraries, but you should not do this. That technique still clutters the global namespace. </p>

<p>There are many options to fix this problem, but the simplest is to create a namespace object and then declare all your functions and properties within it. See the following code snippet for a slightly better approach. </p>

<h4>Object Literal (All Public)</h4>

<p>An Object Literal is a convenient way to create new objects. The syntax looks very similar to what you might expect to see in JSON (JavaScript Object Notation), but they are actually quite different. For more information about this you can check out an in-depth discussion on it by <a href="http://twitter.com/cowboy">Ben Alman</a> entitled <a href="http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/">There's no such thing as a "JSON Object"</a>. </p>

<p>When you create an Object Literal you can provide properties and methods and they can refer to each other. You can also add additional methods and properties to the object after it has been defined. All the properties and methods that you declare in the Object Literal are publicly accessible to the rest of your JavaScript code.</p>

<pre class="brush: jscript;">
//Object Literal declaring properties and methods
var skillet = {
    //public property
    ingredient: &quot;Bacon Strips&quot;,
    
    //public method
    fry: function() {
        console.log( &quot;Frying &quot; + this.ingredient );
    }
};
console.log( skillet.ingredient ); //Bacon Strips
skillet.fry(); //Frying Bacon Strips

//Adding a public property to an Object Literal
skillet.quantity = &quot;12&quot;;
console.log( skillet.quantity ); //12

//Adding a public method to an Object Literal
skillet.toString = function() {
    console.log( this.quantity + &quot; &quot; + 
                 this.ingredient );
};
skillet.toString(); //12 Bacon Strips​
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/ahfgk/8/">jsFiddle</a>.</p>

<p>The above code declares a <code>skillet</code> variable and sets it to an Object Literal with one property (<code>ingredient</code>) and one method (<code>fry</code>) that are both publicly accessible off of the object. You can also add additional public methods and properties to the object after the initial declaration as shown above when adding the <code>quantity</code> property and the <code>toString</code> method. The <code>toString</code> method is able to access the properties of the <code>skillet</code> object since all of it&#8217;s parts are public.</p>

<p>Pros</p>

<ul>
<li>Cleans up the global namespace by adding a namespace to your properties and methods</li>
<li>You can add functionality to the object literal at a later point</li>
<li>All the properties and methods are public</li>
</ul>

<p>Cons</p>

<ul>
<li>Uses the Object Literal syntax to define your properties and methods that some may find cumbersome </li>
<li>There isn&#8217;t the ability to have private properties or methods</li>
</ul>

<h4>Self-Executing Anonymous Function: Part 1 (All Private)</h4>

<p>Another common technique that you can use to protect the global namespace is to use a Self-Executing Anonymous Function. This is just a fancy term to refer to a function with no name that is immediately executed after it&#8217;s defined. The value of this technique is that you can create a wrapper around your code that protects it from the global namespace. By using the most simple version of the Self-Executing Anonymous Function you can create code that is exclusively private.</p>

<pre class="brush: jscript;">
//Self-Executing Anonymous Function: Part 1 (All Private)
(function() {
    //private variable
    var ingredient = &quot;Bacon Strips&quot;;

    //private function
    function fry() {
        console.log( &quot;Frying &quot; + ingredient );
    }
    
    fry();
}());

//Variables not accessible
console.log( window.ingredient ); //Undefined

//Functions not accessible
try {
    window.fry(); //Throws Exception
} catch( e ) {
    //Object [object DOMWindow] has no method 'fry'
    console.log( e.message ); 
}

//Can't add additional functionality
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/zxR3P/8/">jsFiddle</a>.</p>

<p>The above code snippet wraps the <code>ingredient</code> variable and <code>fry</code> function with a Self-Executing Anonymous Function and right before the function ends it executes the <code>fry</code> method. After the Self-Executing Anonymous Function finishes executing there is no way to run the function again or reference any of the internals of the wrapped code.</p>

<p>Pros</p>

<ul>
<li>Hides all your implementation from external code</li>
<li>The function runs once and only once</li>
<li>The code inside doesn&#8217;t use the Object Literal notation</li>
</ul>

<p>Cons</p>

<ul>
<li>All information is hidden, which may not be what you want</li>
<li>Slightly more complicated technique, but not really</li>
</ul>

<h4>Revealing Module Pattern (Public &#038; Private)</h4>

<p>The Revealing Module Pattern actually uses the concept of the Self-Executing Anonymous Function as well, but in this case we save the result into a variable. This pattern introduces the concept of a Closure. A closure is a way to keep variables alive after a function has returned. The Mozilla Developer Network has a <a href="https://developer.mozilla.org/en/JavaScript/Guide/Closures">great page explaining closures</a>. In it they provide a core definition:</p>

<blockquote>
  <p>&#8220;A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created.&#8221;</p>
</blockquote>

<p>In the following example we will declare private properties and methods as well as public properties and methods.</p>

<pre class="brush: jscript;">
//Revealing Module Pattern (Public &amp; Private)
var skillet = (function() {
    var pub = {},
        //Private property
        amountOfGrease = &quot;1 Cup&quot;;

    //Public property    
    pub.ingredient = &quot;Bacon Strips&quot;;

    //Public method
    pub.fry = function() {
        console.log( &quot;Frying &quot; + pub.ingredient );
    };

    //Private method
    function privateWay() {
        //Do something...
    }

    //Return just the public parts
    return pub;
}());

//Public Properties
console.log( skillet.ingredient ); //Bacon Strips

//Public Methods
skillet.fry();

//Adding a public property to a Module
skillet.quantity = 12;
console.log( skillet.quantity ); //12

//Adding a public method to a Module
skillet.toString = function() {
    console.log( skillet.quantity + &quot; &quot; + 
                 skillet.ingredient + &quot; &amp; &quot; + 
                 amountOfGrease + &quot; of Grease&quot; );
};

try {
    //Would have been successful, 
    //but can't access private variable
    skillet.toString();
} catch( e ) {
    console.log( e.message ); //amountOfGrease is not defined
}
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/CDDer/15/">jsFiddle</a>.</p>

<p>Inside of the Revealing Module Pattern we declared a <code>pub</code> object that will keep all the public properties and methods that you want to be exposed. At the end of the Module the <code>pub</code> object is returned, which is what causes the them to be public outside of the Self-Executing Anonymous Function. All the parts that were not added to the <code>pub</code> object remain private to the outside world; however, the public methods that were exposed have access to the private parts because of the Closure that was created. </p>

<p>Pros</p>

<ul>
<li>Allows for public and private properties and methods</li>
<li>The Technique is Easy to understand</li>
<li>The code inside doesn&#8217;t use the Object Literal notation</li>
</ul>

<p>Cons</p>

<ul>
<li>Doesn&#8217;t allow for a way to add private properties to be used in new public methods</li>
</ul>

<h4>Self-Executing Anonymous Function: Part 2 (Public &#038; Private)</h4>

<p>We looked at the Self-Executing Anonymous Function earlier as a pattern you could use to keep all your code private. As it turns out, you can actually modify the pattern somewhat so that you can achieve the same benefits of the Revealing Module Pattern. Not only can we achieve public and private properties and methods, but we can also provide an easy way to extend the namespace while keeping the content protected from the global namespace. In addition, the following pattern can protect the <code>$</code> from conflicting with other JavaScript libraries and also protect <code>undefined</code> from being redefined. </p>

<p>Take a look at the following example, and we will walk through the code explaining the key changes to the pattern.</p>

<pre class="brush: jscript;">
//Self-Executing Anonymous Func: Part 2 (Public &amp; Private)
(function( skillet, $, undefined ) {
    //Private Property
    var isHot = true;

    //Public Property
    skillet.ingredient = &quot;Bacon Strips&quot;;
    
    //Public Method
    skillet.fry = function() {
        var oliveOil;
        
        addItem( &quot;\t\n Butter \n\t&quot; );
        addItem( oliveOil );
        console.log( &quot;Frying &quot; + skillet.ingredient );
    };
    
    //Private Method
    function addItem( item ) {
        if ( item !== undefined ) {
            console.log( &quot;Adding &quot; + $.trim(item) );
        }
    }    
}( window.skillet = window.skillet || {}, jQuery ));

//Public Properties
console.log( skillet.ingredient ); //Bacon Strips

//Public Methods
skillet.fry(); //Adding Butter &amp; Fraying Bacon Strips

//Adding a Public Property
skillet.quantity = &quot;12&quot;;
console.log( skillet.quantity ); //12

//Adding New Functionality to the Skillet
(function( skillet, $, undefined ) {
    //Private Property
    var amountOfGrease = &quot;1 Cup&quot;;
    
    //Public Method
    skillet.toString = function() {
        console.log( skillet.quantity + &quot; &quot; + 
                     skillet.ingredient + &quot; &amp; &quot; + 
                     amountOfGrease + &quot; of Grease&quot; );
        console.log( isHot ? &quot;Hot&quot; : &quot;Cold&quot; );
    };    
}( window.skillet = window.skillet || {}, jQuery ));

try {
    //12 Bacon Strips &amp; 1 Cup of Grease
    skillet.toString(); //Throws Exception
} catch( e ) {
    console.log( e.message ); //isHot is not defined
}
</pre>

<p>You can execute and modify the above code from <a href="http://jsfiddle.net/elijahmanor/MVNBz/22/">jsFiddle</a>.</p>

<p>First, since we have a Self-Executing Anonymous Function, we can actually provide some parameters to pass to it when it executes. In this case we are passing 2 arguments to the anonymous function. </p>

<p>The first argument looks quite strange. What is <code>window.skillet = window.skillet || {}</code> doing? The code checks to see if <code>skillet</code> exists in the global namespace (window). If it does not exist, then <code>window.skillet</code> is assigned an empty object literal. Using this approach we can build a library across JavaScript files. If another script uses the same technique, then it will pass in the existing instance and append logic to it. Inside the Anonymous Function, if we want something to be public, then we append it to the <code>skillet</code> object. Any other properties or methods will be considered private.</p>

<p>The second argument passed in <code>jQuery</code>. The benefit of this is that the named parameter is referenced as <code>$</code>, which allows us to refer to <code>jQuery</code> as <code>$</code> within the Anonymous Function without having to worry that it will conflict with the <code>$</code> declared in other JavaScript libraries. This is a common practice that you will most likely run across when looking at well written jQuery code.</p>

<p>You might notice a 3rd parameter to the Anonymous Function called <code>undefined</code>. Why did we add that parameter and why didn&#8217;t we pass an argument to it? In JavaScript, you can unfortunately redefine what <code>undefined</code> means. Imagine that some code somewhere deep in one of your 3rd party libraries redefines <code>undefined</code> to something strange like <code>true</code>. If anywhere in your code you test against <code>undefined</code>, then you code will most likely not behave like you intended. In JavaScript, if you have a parameter that doesn&#8217;t have a matching argument, then it&#8217;s value is set as <code>undefined</code>. By using this trick, it can save us from the bad code someone wrote to redefine <code>undefined</code>.</p>

<p>Pros</p>

<ul>
<li>Gives you the ability to have public and private properties and methods </li>
<li>The code inside doesn&#8217;t use the Object Literal notation</li>
<li>Keeps undefined&#8217;s value as undefined in case someone overrode the value</li>
<li>Allows you to use $ inside your code without worrying about clashing with other libraries</li>
<li>Allows your library to grow across files using the &#8220;window.namespace = window.namespace || {}&#8221; technique</li>
<li>A common pattern that you will see in many libraries, widgets, and plugins</li>
</ul>

<p>Cons</p>

<ul>
<li>Slightly more complicated pattern, but not overly difficult to understand</li>
</ul>

<p>If you are interested in digging deeper into some of the patterns I mentioned above then I encourage you to check out Klaus Komenda&#8217;s post entitled <a href="http://www.klauskomenda.com/code/javascript-programming-patterns/">JavaScript Programming Patterns</a>. The article provides an insightful view of how JavaScript patterns have changed over the years.</p>

<h4>Best Practice</h4>

<p>In JavaScript it is very important to declare all of your variables and it is considered a best practice to limit the number of objects in the global namespace. Depending on the situation you are developing you may need one or more of the concepts listed above to organize your code and keep it from colliding with other libraries. There is no pattern that is a Silver Bullet, but rather you should assess where you are at and examine the pros and cons of each pattern to address your situation.</p>

<h3>2. Not Declaring Arrays &#038; Objects Correctly</h3>

<p>JavaScript is a prototypal language and not a classical language like C#. Although JavaScript does have a new operator which looks a lot like C#, you should not use it for creating new objects or arrays.</p>

<h4>What Not To Do</h4>

<p>You might be tempted to use the <code>new</code> keyword to create your objects in JavaScript.</p>

<pre class="brush: jscript;">
//Bad way to declare objects and arrays
var person = new Object(), 
    keys = new Array();
</pre>

<p>The <code>new</code> keyword was added to the language partially to appease classical languages, but in reality it tends to confuse developers more than help them. Instead, there are native ways in JavaScript to declare objects and arrays and you should use those instead.</p>

<h4>Preferred Way</h4>

<p>Instead of using the previous syntax, you should instead declare your objects and arrays using their literal notation.</p>

<pre class="brush: jscript;">       
//Preferred way to declare objects and arrays
var person = {}, 
    keys = [];
</pre>      

<p>Using this pattern you actually have a lot of expressive power using Object Literals and array initializer syntax. As we mentioned earlier, you should be careful to know that Object Literals are not JSON. </p>

<pre class="brush: jscript;">
//Preferred way to declare complex objects and arrays
var person = {
        firstName: &quot;Elijah&quot;,
        lastName: &quot;Manor&quot;,
        sayFullName: function() {
            console.log( this.firstName + &quot; &quot; + 
                this.lastName );
        }
    }, 
    keys = [&quot;123&quot;, &quot;676&quot;, &quot;242&quot;, &quot;4e3&quot;];
</pre>

<h4>Best Practice</h4>

<p>You should declare all of your variables using their literal notation instead of using the <code>new</code> operation. In a similar fashion you shouldn&#8217;t use the new keyword for <code>Boolean</code>, <code>Number</code>, <code>String</code>, or <code>Function</code>. All they do is add additional bloat and slow things down. </p>

<p>The only real reason why you would use the new keyword is if you are creating a new object and you want it to use a constructor that you defined. For more information on this topic you can check out <a href="http://www.crockford.com/">Douglas Crockford's</a> post entitled <a href="http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/">JavaScript, We Hardly new Ya</a>.</p>

<h2>Conclusion</h2>

<p>This article has covered some of the common issues you might address coming from C# to JavaScript. I have committed just about everyone of the above Bad Practices myself when I starting to code in JavaScript heavily. </p>

<p>With the recent serge of jQuery hitting the market and other great JavaScript libraries, it is important that we as developers understand the language instead of just thinking that our previous language knowledge will get us by. </p>

<p>This article only covers some of the things you should know. The next post in the series will be published next week. In the meantime please feel free to add comments of any other gotchas that you&#8217;ve experience coming from a C# background. I would love to hear about it. </p>

<div class="note">
<p>The <a href="http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2">second post</a> covers the following topics:</p> 
<ul>
    <li>3. Not Understanding False-y Values</li>
        <li>4. Not Testing &amp; Setting Default Values Correctly</li>
    <li>5. Using the Wrong Comparison Operators</li>
    <li>6. Not Using the For…In Statement Correctly</li>
</ul>
</div>
]]></content:encoded>
			<wfw:commentRss>http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/feed/</wfw:commentRss>
		<slash:comments>35</slash:comments>
		</item>
		<item>
		<title>Creating an Ajax Component:Handling Errors and Loading Notifications with Publish and Subscribe</title>
		<link>http://enterprisejquery.com/2010/09/creating-an-ajax-component-handling-errors-and-loading-notifications-with-publish-and-subscribe/</link>
		<comments>http://enterprisejquery.com/2010/09/creating-an-ajax-component-handling-errors-and-loading-notifications-with-publish-and-subscribe/#comments</comments>
		<pubDate>Tue, 28 Sep 2010 18:43:36 +0000</pubDate>
		<dc:creator>Andrew Wirick</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Multipart Series]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://enterprisejquery.com/?p=530</guid>
		<description><![CDATA[This is the second post in a multi-part series on creating a JavaScript component for handling your Ajax requests in front-end development across your enterprise. You can find the first post here: Post 1: From Enterprise Beginnings In the last post we covered some introductory topics for creating your own JavaScript utility library, which wraps [...]
]]></description>
			<content:encoded><![CDATA[<div class="note">This is the second post in a multi-part series on creating a JavaScript component for handling your Ajax requests in front-end development across your enterprise. You can find the first post here:
<ul>
    <li><a href="http://enterprisejquery.com/2010/07/enterprise-ajax-patterns-part-1-from-enterprise-beginnings/">Post 1: From Enterprise Beginnings</a></li>
</ul>
</div>

<p>In the last post we covered some introductory topics for creating your own JavaScript utility library, which wraps functionality for Ajax. We&#8217;ll start where we left off. Our first step will be to add a few tweaks to our library to make it more usable:</p>

<pre class="brush: jscript;">
var mySiteAjax = ( function( $ ) {
  return (
     function( params ){
      var settings = $.extend({
        url: &quot;&quot;, 
        spinner:  undefined, 
        dataType: &quot;html&quot;,
        data: &quot;&quot;,
        type: &quot;GET&quot;,
        cache:  false,
        success:  function() { }
      }, params );

      $.ajax({
          beforeSend: function() { 
            $( settings.spinner ).show();
          },
          url: settings.url,
          dataType: settings.dataType,
          type: settings.type,
          data: setting.data,
          success: settings.success,
          complete: function() {
              $( settings.spinner ).hide();
            }      
        });
    } 
  );
})(jQuery);
</pre>

<p>We&#8217;ve done two things to our old example. We&#8217;ve added new parameters for type and data that could be passed in. Additionally, we&#8217;ve removed a named function and returned an object literal. This enables easier usage:</p>

<pre class="brush: jscript;">
mySiteAjax({
  url: &quot;myUrl&quot;,
  success: function( data ) {
    //do something with the data here
  }
});
</pre>

<p>Although a good start, this solution is not yet satisfactory as we are not yet handling errors in any capacity. How do we handle errors and display messages to the user? Additionally showing and hiding of loading notification images is present but not customizable. What if a page doesn&#8217;t want to do a simple showing and hiding of load images? How can we decouple the notifications from our Ajax component library?</p>

<p><span id="more-530"></span></p>

<h2>Handling and Displaying Errors</h2>

<p>When dealing with Ajax errors there are typically two concerns &#8211; handling the error in code and displaying an error message to the user.</p>

<h3>Handling the Ajax Error</h3>

<p>A popular technique for &#8220;handling&#8221; Ajax errors is to either never add an error callback for the Ajax request, or to end up with code like this (including the todo comment):</p>

<pre class="brush: jscript;">
$.ajax({
  //...
  error: function() {
    // todo: handle error here.
  },
  //...
});
</pre>

<p>Most of us have been there. It is often a struggle to determine what reasonable actions can be done with an Ajax error. Yet there are some options. A few pragmatic actions we could take upon Ajax error:</p>

<ul>
<li>Try again (especially for GETs).</li>
<li>Have debug code for non-production code which logs the error details to the console.</li>
<li>Have an error specific Ajax request URL (either global for all sites or specific to your application). This activity is typically a request in which data is sent to the server and the client does not care about the response. This is typically used to log the issue to a server-side resource.</li>
<li>Automatically take action based on HTTP Status Code. We can detect certain error codes from the server response and take action. For example a 401 or 403 error may be an indication of expired client credentials. In this case we could redirect the user to a login page to establish new credentials.</li>
<li>Suggest to the user next steps as part of the error message.</li>
</ul>

<p>It would be prudent for our utility library to take some actions based upon HTTP status code. If the user request comes in as unauthorized we will redirect to a new page. If there is a server timeout we will try the Ajax request a second time.</p>

<p>To accomplish this we need to add an error callback function to <code>.ajax()</code>. We are also going to add another programming technique to repeatedly call <code>.ajax()</code>. First the code:</p>

<pre class="brush: jscript;">
var mySiteAjax = ( function( $ ) {
  return (
    function( params ) {
      //...
      var retries = 0;
      function ajaxRequest ( ) {
        $.ajax({
          beforeSend: function(){ 
            $(settings.spinner).show();
          },
          url: settings.url,
          dataType: settings.dataType,
          success: settings.success,
          complete: function(){
            $( settings.spinner ).hide();
          },
          error: function( xhr, tStatus, err ) {
            if( xhr.status === 401 || xhr.status === 403 ) {
              //redirect action here
            } else if ( xhr.status === 504 &amp;&amp; !retries++ ) {
              ajaxRequest();
            }
          } // end error handler
        }); // end $.ajax()
      }; // end ajaxRequest() 
      ajaxRequest();
    } // end getViaAjax()
  ); // end return statement
})(jQuery);
</pre>

<p>We&#8217;re using the status property of the XmlHttpRequest object to determine the type of error encountered. With our authorization issues we can detect an authorization error status code and redirect to our authorization page. Handling retries requires us to call the original Ajax call again. To do that we can use <a href="http://en.wikipedia.org/wiki/Recursion">recursion</a>.</p>

<p>In our case of recursion we are setting up a <code>retries</code> variable to determine the number of Ajax requests we setup. <code>retries</code> is declared outside of the recursive function. We can use and increment the <code>retries</code> variable inside of our function because of <a href="https://developer.mozilla.org/en/JavaScript/Guide/Closures">lexical scoping</a>. If retries is 0 and a timeout error code occurs, we increment retries and recursively call ajaxRequest. The ajaxRequest function then sets up a another ajax request. If another timeout occurs  <code>retries</code> is now set to 1 which will keep another recursive call from happening.</p>

<p>After we&#8217;ve created our ajaxRequest function we then execute it to kick off an initial Ajax request.</p>

<p>We&#8217;re not using the global event handler, <code>.ajaxError()</code>. This is because we only want our error handling to affect those calls which come through our component. If we attach a handler globally using <code>.ajaxError()</code> then all ajax errors will result in the execution of our callback. While you may want that behavior in your application, it&#8217;s generally considered bad practice to introduce code with side effects.
<div class="note">This example gets us started down the path of retries, but isn&#8217;t a <em>complete</em> solution. Other good additions would be to allow the number of retries to be specified as a parameters, and to add timers to throttle retries.</div></p>

<h3>Displaying Error Messages to the User</h3>

<p>Notifying the user of the error involves interaction with another component on the page (you can find an example of creating such a component with our message center plugin blog posts <a href="http://enterprisejquery.com/2010/07/create-your-first-jquery-plugin-part-1-transition-from-everyday-jquery-code-to-base-plugin/">1</a> and <a href="http://enterprisejquery.com/2010/07/create-your-first-jquery-plugin-part-2-revising-your-plugin/">2</a>).  We could set up another parameter to be passed as an error callback function. However, it seems like we&#8217;re quickly going parameter-happy.</p>

<p>We&#8217;re already expecting the calling code of our utility function to know about the load notifications (spinners) that may be on the page. We&#8217;d be adding yet another responsibility of the callee to know which and how many messaging components may be on the page and would need to be notified of an Ajax error. This puts pressure on the code calling our Ajax library to be edited every time any messaging or loading notification widgets are added, edited, or removed from the page.</p>

<h3>Paradigm Shift &#8211; Communicating Between Components with Publish/Subscribe</h3>

<p>In our case we have three separate components that are trying to interact on the page:</p>

<ul>
<li>An Ajax system</li>
<li>A &#8216;loading&#8217; notification system</li>
<li>A flash message or message center</li>
</ul>

<p>We need an effective way to communicate between components. In the case of our Ajax library, we need to notify any components that an error message is available to be displayed or that a load notification needs to start or end.</p>

<h3>Introducing Publish/Subscribe</h3>

<p>A great solution would be to broadcast over a channel that an error occurred or that loading has started. Consumers could register a callback to run when a message was broadcast over a specific channel.</p>

<p>One way to accomplish this is the <a href="http://en.wikipedia.org/wiki/Publish/subscribe">publish/subscribe pattern</a>. With this pattern a publish function typically exists which broadcasts using a message topic. A subscribe function is used to bind a callback function which will be executed when a message topic is broadcast. Data can be passed to the subscriber through an additional parameter.</p>

<p>If we compare a typical publish/subscribe system to a radio broadcast, the &#8220;message topic&#8221; would be the selected AM, FM, or Satellite station. The data being passed to the subscriber would be analogous to the audio coming through the radio.</p>

<h4>Using Custom jQuery Events for Publish and Subscribe</h4>

<p>We can illustrate publishing and subscribing by using jQuery custom events names. We can use the event name as our message topic and pass data using the additional parameters.</p>

<p>Lets add a mechanism to publish error messages as well a standard error message:</p>

<pre class="brush: jscript;">
var mySiteAjax = ( function( $ ) {
  var standardError = &quot;Oops. Sorry about that.&quot;;
  return (
    function( params ) {
      var settings = $.extend({
        url:      '', 
        spinner:  undefined, 
        dataType: 'html',
        cache:    false,
        success:  function(){}
      }, params);

      var retries = 0;
      function ajaxRequest ( ) {
        $.ajax({
          beforeSend: function(){ 
            $(settings.spinner).show();
          },
          url: settings.url,
          dataType: settings.dataType,
          success: settings.success,
          complete: function(){
            $( settings.spinner ).hide();
          },
          error: function( xhr, tStatus, err ) {
            if( xhr.status === 401 || xhr.status === 403 ) {
              //redirect action here
            } else if ( xhr.status === 504 &amp;&amp; !retries++ ) {
              ajaxRequest();
            }
            $(document).trigger( &quot;ui-flash-message&quot;, 
              [{ message: standardError }] );
          } // end error handler
        }); // end $.ajax()
      }; // end ajaxRequest() 
      ajaxRequest();
    } // end getViaAjax()
  ); // end return statement
})(jQuery);
</pre>

<p>We&#8217;re publishing with a custom event named &#8220;ui-flash-message&#8221;. The <code>.trigger()</code> method takes in an array of parameters as a second argument. We chose to pass in a single hash (object literal) with our message attached.</p>

<p>Now that we&#8217;ve covered publishing, lets take a look at how a subscribe might be set up:</p>

<pre class="brush: jscript;">
  // ... somewhere in a component that displays messages
  $(document).bind( &quot;ui-flash-message&quot;,
    function(evt, data) {
      if(data.message) {
        showMessage(data.message);
      }
    };
   // ... 
</pre>

<p>Our subscriber must be set up before a message is published. In this case as long as our message component has already been loaded and the above code has been executed, then the component is waiting for a message to be published.</p>

<h3>Load Notifications</h3>

<p>Our old implementation of load notification was for a selector to be passed in and our Ajax component would handle the showing and hiding of a &#8216;spinner&#8217;. This technique is not ideal. The Ajax component has no business implementing specific behavior for spinners (such as using <code>.show()</code> and <code>.hide()</code>). It would be much better to use our publish/subscribe methodology to allow other components to handle the behavior.</p>

<pre class="brush: jscript;">
// we 'define' undefined to alleviate concerns
// that someone may have done something stupid
// like this in code before this code executes:
// undefined = &quot;Im now defined.&quot;;
// credit: Ben Alman (see comments)
var mySiteAjax = ( function( $, undefined ) {
  return (
    function( params ) {

      // use extend to merge our defaults with parameters
      // passed by function caller
      var settings = $.extend({
        url: &quot;&quot;,
        spinner:  {}, 
          // use empty object if version 1.3.2-
          // credit: Ben Alman (see comments)
        dataType: &quot;html&quot;,
        cache:    false,
        success:  function(){},
        errorMsg: &quot;Oops. Sorry about that.&quot; 
          // credit: rmurphey (see comment below)
      }, params),
          retries = 0; // setting up retries variable
     // setting up a function that we can call recursively
     // to retry ajax calls 
     function ajaxRequest ( ) {
        alert(&quot;here&quot;);
        $.ajax({
          beforeSend: function() { 
            $( settings.spinner ).show();
          },
          url: settings.url,
          dataType: settings.dataType,
          success: settings.success,
          complete: function() {
            $( settings.spinner ).hide();
          },
          error: function( xhr, tStatus, err ) {
            if( xhr.status === 401 || xhr.status === 403 ) {
              //redirect action here
            } else if ( xhr.status === 504 &amp;&amp; !retries++ ) {
              //make our recursive request
              ajaxRequest();
            } else {
              $(document).trigger( &quot;ui-flash-message&quot;, 
                [{ message: settings.errorMsg }] );
            }
          } // end error handler
        }); // end $.ajax()
      }; // end ajaxRequest() 
      
      // call our ajax request function. notice above
      // that we only define the function. here we make
      // the original call.
      ajaxRequest();
        
    } // end getViaAjax()
  ); // end return statement
})(jQuery);
</pre>

<p>Now we can add a load notification component to our application, where we can handle showing and hiding spinners:</p>

<pre class="brush: jscript;">
  // ... somewhere in a load component
  $(document).bind( &quot;ui-load-start-message&quot;,
    function(evt, data) {
      $(data.spinner).show();
    });

  $(document).bind( &quot;ui-load-end-message&quot;,
    function(evt, data) {
      $(data.spinner).hide();
    });
   // ... 
</pre>

<p>We now have much better separation of concerns. The Ajax component only publishes messages and isn&#8217;t concerned with implementation of a loading notification system.</p>

<p>I&#8217;ve set an example of this solution on a <a href="http://jsfiddle.net/paGJR/14/">jsFiddle</a> with a few use cases. Take a look at the example and feel free to play with the functionality on your own. Post in the comments if you find anything interesting!</p>

<p>Although you can create a message bus with jQuery custom events, there&#8217;s overhead and DOM interaction that isn&#8217;t necessary. Components exist today that allow for publish/subscribe to occur using only JavaScript. I encourage you to look for those components and use them for publish and subscribe interactions.</p>

<p>PostScript / Errata :
There have been some good comments below, so we&#8217;ve made a few changes:</p>

<ul>
<li>The last full Ajax solution has been updated with suggestions and appropriate credit given.</li>
<li>The jsFiddle has been updated to reflect those changes.</li>
<li>Rebecca Murphey correctly pointed out that we are adding a variable to the global scope and that is something that should be minimized. A good approach would be to create a simple namespace (object) and add this utility library to that namespace. So the assignment at the top statement wouldn&#8217;t be <code>mySiteAjax</code>, but rather <code>myCompanyNS.siteAjax</code> or something similar. Note that you&#8217;ll need to ensure <code>myCompanyNS</code> exists and created an empty object if it does not already. We are still adding to the global scope, but one is better than many possible editions.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://enterprisejquery.com/2010/09/creating-an-ajax-component-handling-errors-and-loading-notifications-with-publish-and-subscribe/feed/</wfw:commentRss>
		<slash:comments>30</slash:comments>
		</item>
		<item>
		<title>Enterprise Strategies for Adopting HTML5 Part 1:Simplified Syntax &amp; Semantic Elements</title>
		<link>http://enterprisejquery.com/2010/08/enterprise-strategies-for-adopting-html5-part-1-simplified-syntax-semantic-elements/</link>
		<comments>http://enterprisejquery.com/2010/08/enterprise-strategies-for-adopting-html5-part-1-simplified-syntax-semantic-elements/#comments</comments>
		<pubDate>Wed, 18 Aug 2010 16:45:32 +0000</pubDate>
		<dc:creator>Elijah Manor</dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Multipart Series]]></category>

		<guid isPermaLink="false">http://enterprisejquery.com/?p=326</guid>
		<description><![CDATA[This is the first post of a multi-part series covering strategies that you might use to adopt HTML5 in your current or future corporate websites. Introduction HTML5 has many features which you’ve likely heard about or seen in various blog posts. With all of the publicity HTML5 has begun to hold weight as a marketing [...]
]]></description>
			<content:encoded><![CDATA[<div class="note"><p>This is the first post of a multi-part series covering strategies that you might use to adopt HTML5 in your current or future corporate websites.</p></div>

<h2>Introduction</h2>

<p>HTML5 has many features which you’ve likely heard about or seen in various blog posts. With all of the publicity HTML5 has begun to hold weight as a marketing term and businesses are paying attention. In the near future we&#8217;ll see businesses want to leverage HTML5 to send a message that they are innovative and competitive.</p>

<p>Unfortunately many of the HTML5 features are not fully implemented in the newest versions of modern browsers.  Older browsers lack any HTML5 support.  This leaves us with a key question: &#8220;To what extent can I use HTML5 inside my enterprise application?&#8221;  </p>

<p>In this blog series we will deliver a strategy you can use to start adopting HTML5 <em>today</em>.  We&#8217;ll break down the strategy into the following posts: </p>

<ul>
<li>Part 1: Simplified Syntax &#038; Semantic Elements</li>
<li>Part 2: Form Enhancements</li>
<li>Part 3: Local &#038; Session Storage: </li>
</ul>

<p style="margin: 0px 15px 15px 50px; font-style: italic;">Client storage is no longer part of the HTML5 specification. Nevertheless we&#8217;ve decided to cover client storage as it is still popular as a topic in HTML5 discussions and is implemented in many of the modern browsers.</p>

<ul>
<li>Part 4: Video &#038; Audio Elements</li>
</ul>

<p><span id="more-326"></span></p>

<h2>Simplified Syntax</h2>

<div class="note"><p>All of the techniques that are shown in this section (DOCTYPE, Encoding, Script, Style, and Link) work in current and past browsers. No additional work is necessary to provide this support. We recommend you adopt these changes now and only use the old syntax if you have a specific reason to do so.</p></div>

<h3>Simplified DOCTYPE</h3>

<p>Selecting a DOCTYPE is a necessary part of building a web page. There are many to choose from depending on how you compose your markup. Here is a list of several common DOCTYPEs you may have seen.</p>

<h4>Old Way</h4>

<pre class="brush: xml;">
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot;
  &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;

&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;
  &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;

&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot;
  &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&quot;&gt;

&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Frameset//EN&quot;
  &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd&quot;&gt;

&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot;
  &quot;http://www.w3.org/TR/html4/strict.dtd&quot;&gt;

&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Frameset//EN&quot;
  &quot;http://www.w3.org/TR/html4/frameset.dtd&quot;&gt;
</pre>

<p>Some developers and designers know what all of those DOCTYPEs mean, but I would guess that many don’t. Even if they knew what they meant it can even more difficult to understand which situations warrant each DOCTYPE. I&#8217;ve seen many situations in corporations where a developer copies and pastes a DOCTYPE from another document or will use a template and never think about it. </p>

<p>You can find more information about all of these DOCTYPEs and browser modes in an interesting write up from <a href="http://twitter.com/hsivonen">Henri Sivonen</a> entitled <a href="http://hsivonen.iki.fi/doctype/">Activating Browser Modes with Doctype</a>.</p>

<h4>New HTML5 Way</h4>

<pre class="brush: xml;">
&lt;!DOCTYPE html&gt;
</pre>

<p>Thankfully this is a much simpler way to declare the DOCTYPE. We now have one DOCTYPE to chose from and it is short and sweet.</p>

<p>I&#8217;ve already mentioned that we can use this new DOCTYPE today.  But what about older browsers? If clients use a browser that doesn’t recognize the HTML5 DOCTYPE then it will switch the content into standards mode and not quirks mode. Unless you have a specific reason to cater to browser modes, start using the new DOCTYPE declaration and take advantage of all the HTML5 goodness in your web application.</p>

<h3>Simplified Encoding</h3>

<p>HTML5 has also provided a simplified approach in the the way we indicate the character encoding used for the document. </p>

<h4>Old Way</h4>

<pre class="brush: xml;">
&lt;meta http-equiv=&quot;Content-Type&quot; 
  content=&quot;text/html; charset=utf-8&quot;&gt;
</pre>

<h4>New HTML5 Way</h4>

<pre class="brush: xml;">
&lt;meta charset=&quot;utf-8&quot;&gt;
</pre>

<p>Interestingly current and older browsers already support this shortened syntax and we can use it right away in web applications. You can read more about this and other interesting details from <a href="http://twitter.com/diveintomark">Mark Pilgrim</a>&#8217;s detailed explanation in <a href="http://diveintohtml5.org/semantics.html">Dive into HTML 5: What Does It All Mean?</a>.</p>

<h3>Simplified Script, Style, and Link elements</h3>

<p>Another simplification in HTML5 is to make the type parameter optional on the script, style, and link elements. If we don’t provide the type attribute, then their defaults will be “text/javascript” for script tags and “text/css” for style and link tags. That means that we can leave out the type attribute in the majority of our uses of these elements. The great thing is that we can also use these techniques today in our web site and it will be supported in older browsers as well. </p>

<h4>Old Way</h4>

<pre class="brush: xml;">
&lt;link rel=&quot;stylesheet&quot; href=&quot;site.css&quot; type=&quot;text/css&quot; /&gt;
&lt;style type=&quot;text/css&quot;&gt;
  h1 { color: red; }
&lt;/style&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;common.js&quot;&gt;&lt;/script&gt;
</pre>

<h4>New HTML5 Way</h4>

<pre class="brush: xml;">
&lt;link rel=&quot;stylesheet&quot; href=&quot;site.css&quot; /&gt;
&lt;style&gt;
  h1 { color: red; }
&lt;/style&gt;
&lt;script src=&quot;common.js&quot;&gt;&lt;/script&gt;
</pre>

<h2>Semantic Elements</h2>

<div class="note"><p>The following section includes new HTML5 technologies that we can use today as well as the work arounds we can implement to obtain older browser support.</p></div>

<p>There was a time when websites were commonly designed by using table element after table element to create complex layouts. Recently most designers heavily use the div element to float their way to equally complex and versatile layouts. HTML5 continues to transition web design by introducing new elements that make layouts more explicit.</p>

<h3>New HTML5 Elements</h3>

<p>Instead of overly using divs across our web application we can use the new HTML5 <code>header</code>, <code>footer</code>, <code>article</code>, <code>section</code>, <code>nav</code>, <code>menu</code>, and <code>hgroup</code> elements. These additions are more semantics than anything else. We could just as easily keep them as divs, but by using the new elements it makes your markup much more recognizable and easier to navigate.</p>

<p>Let’s take a simple scenario and see how it changes our markup. A common thing to include in a website is a header section. Normally we just use a <code>div</code> element and give it an id of “header”. However, we can just use the new semantic HTML5 element <code>header</code> instead.</p>

<h4>Old Way</h4>

<pre class="brush: xml;">
&lt;div id=&quot;header&quot;&gt;
  &lt;h1&gt;Welcome to My Blog&lt;/h1&gt;
  &lt;h2&gt;Random Thoughts of a Programmer&lt;/h2&gt;
&lt;/div&gt;
</pre>

<p><a href="http://jsbin.com/ajici4/4/edit">JS Bin demo</a></p>

<h4>New HTML5 Way</h4>

<pre class="brush: xml;">
&lt;header&gt;
  &lt;hgroup&gt;
    &lt;h1&gt;Welcome to My Blog&lt;/h1&gt;
    &lt;h2&gt;Random Thoughts of a Programmer&lt;/h2&gt;
  &lt;/hgroup&gt;
&lt;/header&gt;
</pre>

<p><a href="http://jsbin.com/ageti/3/edit">JS Bin demo</a></p>

<p>Other than simply just replacing the <code>div</code> element with a HTML5 <code>header</code> element, you might also notice that I introduced the idea of using a <code>hgroup</code> element. This is another new HTML5 element that is meant to group section headings (i.e. <code>h1</code>, <code>h2</code>, <code>h3</code>, etc&#8230;). The benefit of this is that the items in the <code>hgroup</code> don&#8217;t affect the overall outline of the document. This means that we can have a heading and sub-heading without changing the outline layout of the document.</p>

<h2>Support for Older Browsers</h2>

<p>As long as a client is using a browser that can understand HTML5 our page will render properly.  When someone renders our updated website with a non-HTML5 complaint browser (such as Internet Explorer), there are some things that we’ll need to consider.</p>

<p>Current released versions of Internet Explorer can’t understand the new HTML5 elements, so we&#8217;ll need to add some additional JavaScript code to help. We can either create the HTML5 elements manually, use the <a href="http://www.modernizr.com/">HTML5 Shiv</a> library, or use the <a href="http://www.modernizr.com/">jQuery Modernizr Plugin</a>. Let&#8217;s cover each of these in more detail.</p>

<div class="note"><p>Internet Explorer 9 is intended to support HTML5 but it is currently only in the early phase of development. The beta version of Internet Explorer 9 will be released on <a href="http://mashable.com/2010/08/12/ie9-beta/">September 15, 2010</a>. Until then you can download the <a href="http://ie.microsoft.com/testdrive/">latest preview bits</a> and play around with them. </p></div> 

<h3>Creating HTML5 Elements Manually</h3>

<p>We can always create the HTML5 elements manually. It isn’t difficult to do. We just need to call the createElement method off the of the document and pass the new element’s name. At that point, the browser will recognize the new element and be able to apply styles to it.</p>

<pre class="brush: jscript;">
document.createElement(&quot;header&quot;);  
document.createElement(&quot;footer&quot;);  
//etc...
</pre>

<h3>Creating HTML5 Elements with HTML5 Shiv</h3>

<p>Why do something by hand when someone has already done it for us? <a href="http://twitter.com/rem">Remy Sharp</a> has created a library called <a href="http://code.google.com/p/html5shiv/">HTML5 Shiv</a> that already does the manual creation of HTML5 elements for us. The library is hosted on Google Code and we can integrate it in our project by including the following lines in the head section of the document.</p>

<pre class="brush: xml;">
&lt;!--[if lt IE 9]&gt;
&lt;script src=&quot;http://html5shiv.googlecode.com/svn/trunk/html5.js&quot;&gt;&lt;/script&gt; 
&lt;![endif]--&gt;
</pre>

<h3>Creating HTML5 Elements with Modernizr</h3>

<p>Another way that we can create the new HTML5 elements is to use the <a href="http://www.modernizr.com/">Modernizr JavaScript Library</a> that <a href="http://twitter.com/paul_irish">Paul Irish</a> and <a href="http://twitter.com/KuraFire">Faruk Ateş</a> developed. The library creates all the new HTML5 elements we need while it is loading on the page. All we need to do is to include the script tag inside of the head element before we style our HTML5 elements.</p>

<pre class="brush: xml;">
&lt;script src=&quot;modernizr-1.5.min.js&quot;&gt;&lt;/script&gt;
</pre>

<p>The library really does much more than just create the new HTML5 elements. Its purpose is to detect which features a client browser supports and allows us to develop your web application using progressive enhancement techniques. The scope of the plugin is much too large for this particular blog post, but I encourage you to check it out.</p>

<p>If you plan to use some of the advanced features of Modernizr, then it will already create the new HTML5 elements for you. If you don&#8217;t plan on customizing the experience based on the features of the current browser, then your best bet is to use the HTML5 Shiv or manually create the HTML5 elements yourself in code.</p>

<h3>Styling the HTML5 Elements</h3>

<p>Now that we’ve managed to make older browsers understand the HTML5 elements we need to focus on styling them correctly. </p>

<p>On creation the elements will have a default display style of “inline”. In order to style them correctly we&#8217;ll likely need to change their style to “block” instead. This can be done very easily with the following section of code.</p>

<pre class="brush: xml;">
header, footer, article, section, nav, menu, hgroup {  
  display: block;  
}  
</pre>

<h3>Dynamic Insertion of HTML5 Elements</h3>

<p>As, it turns out there is another caveat that we need to account for when using HTML5 elements in Internet Explorer. If we try to add HTML5 elements to the DOM dynamically it will not recognize the new element and therefore won’t style it appropriately.</p>

<p>Thanks to <a href="http://twitter.com/jdbartlett">Joe Bartlett</a>, there is a script called <a href="http://jdbartlett.github.com/innershiv/">HTML5 innerShiv</a> that will resolve this issue. You can find more information about usage of this script on <a href="http://twitter.com/chriscoyier">Chris Coyier</a>’s blog post entitled <a href="http://css-tricks.com/html5-innershiv/">Fix Inserted HTML5 Content with HTML5 innerShiv</a>.</p>

<p>For example, instead of just appending a new HTML5 element to the DOM, we would first wrap it in the innerShiv method.  </p>

<pre class="brush: jscript;">
$('header').append(innerShiv(&quot;&lt;nav&gt;&lt;ul&gt;&lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;archives.html&quot;&gt;Archives&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/nav&gt;&quot;));
</pre>

<h2>A Larger Before vs After Example using HTML5 Semantic Elements</h2>

<div class="note"><p>The intent of this section is not to explain the nuances of when and when not to use each of the new HTML5 Semantic Elements, but it is rather an example of how a layout could be changed utilizing the new elements. You can learn more details about each of the HTML5 elements from the <a href="http://html5doctor.com/glossary/">HTML5 Doctor Glossary</a>.</p></div>

<p>To give you an idea of how the format of your page layout might change, I&#8217;ve included the following markup snippets. The first code snippet shows how you might organize the markup with HTML 4 and the following snippet shows how you might organize it with the new HTML5 semantic elements. </p>

<h4>Old Way</h4>

<pre class="brush: xml;">
&lt;div id=&quot;header&quot;&gt;
  &lt;h1&gt;Welcome to My Blog&lt;/h1&gt;
  &lt;h2&gt;Random Thoughts of a Programmer&lt;/h2&gt;
  &lt;div id=&quot;navigation&quot;&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;archives.html&quot;&gt;Archives&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/div&gt;
&lt;/div&gt;
&lt;div id=&quot;sidebar&quot;&gt;
  &lt;h1&gt;Twitter&lt;/h1&gt;
  &lt;blockquote cite=&quot;http://twitter.com/elijahmanor/status/20313555458&quot;&gt;
  1st day at @appendTo I wrote Aug Tips for @ejquery website. Let me know if you found helpful, thnx http://j.mp/ejquery
  &lt;/blockquote&gt;
&lt;/div&gt;
&lt;div id=&quot;posts&quot;&gt;
  &lt;div class=&quot;post&quot;&gt;
    &lt;div class=&quot;header&quot;&gt;
      &lt;h3&gt;I'm looking for a Job&lt;/h3&gt;
    &lt;/div&gt;
    &lt;div class=&quot;content&quot;&gt;
      &lt;p&gt;Well, it's a funny story involving the FBI and IRS raiding...&lt;/p&gt;
    &lt;/div&gt;
    &lt;div class=&quot;footer&quot;&gt;
      &lt;p&gt;Published &lt;time pubdate datetime=&quot;2010-07-08T12:21-07:00&quot;&gt;8, July 2010&lt;/time&gt;.&lt;/p&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;footer&quot;&gt;
  &lt;ul&gt;
    &lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;archives.html&quot;&gt;Archives&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;
</pre>

<h4>New HTML5 Way</h4>

<pre class="brush: xml;">
&lt;header&gt;
  &lt;hgroup&gt;
    &lt;h1&gt;Welcome to My Blog&lt;/h1&gt;
    &lt;h2&gt;Random Thoughts of a Programmer&lt;/h2&gt;
  &lt;/hgroup&gt;
  &lt;nav&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;archives.html&quot;&gt;Archives&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/nav&gt;
&lt;/header&gt;
&lt;aside&gt;
  &lt;h1&gt;Twitter&lt;/h1&gt;
  &lt;blockquote cite=&quot;http://twitter.com/elijahmanor/status/20313555458&quot;&gt;
  1st day at @appendTo I wrote Aug Tips for @ejquery website. Let me know if you found helpful, thnx http://j.mp/ejquery
  &lt;/blockquote&gt;
&lt;/aside&gt;
&lt;section&gt;
  &lt;article&gt;
    &lt;header&gt;
      &lt;h3&gt;I'm looking for a Job&lt;/h3&gt;
    &lt;/header&gt;
    &lt;content&gt;
      &lt;p&gt;Well, it's a funny story involving the FBI and IRS raiding...&lt;/p&gt;
    &lt;/content&gt;
    &lt;footer&gt;
      &lt;p&gt;Published &lt;time pubdate datetime=&quot;2010-07-08T12:21-07:00&quot;&gt;8, July 2010&lt;/time&gt;.&lt;/p&gt;
    &lt;/footer&gt;
  &lt;/article&gt;
&lt;/section&gt;
&lt;footer&gt;
  &lt;ul&gt;
    &lt;li&gt;&lt;a href=&quot;index.html&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;archives.html&quot;&gt;Archives&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;
&lt;/footer&gt;
</pre>

<h2>Templates to Get You Started</h2>

<p>Recently three separate projects have formed to help you get quickly started with HTML5 development in your next project. These projects address many of the concerns we&#8217;ve addressed above, but also touch on topics that we haven&#8217;t yet addressed. </p>

<ul>
<li><a href="http://html5boilerplate.com/">HTML5 Boilerplate</a> by <a href="http://twitter.com/paul_irish">Paul Irish</a> and <a href="http://twitter.com/nimbupani">Divya Manian</a> &#8211; This template is probably the most comprehensive I&#8217;ve seen. It includes a host of features that you&#8217;ll need to start a new HTML5 web application. It addresses the concerns we&#8217;ve mentioned in this article, but it also handles mobile optimizations, optimal caching rules, progressive enhancement using Modernizr, CDN hosted jQuery with local failsafe, plus much more. You&#8217;ll most likely use this template as a starting point and then delete the things that may not be pertinent to your web application.</li>
<li><a href="http://html5reset.org/">HTML5 Reset</a> &#8211; This template is slightly less comprehensive as the Boilerplate, but still provides a great amount of features that you&#8217;ll most likely need in your next HTML5 web application. Some of these features include cross-browser concerns, progressive enhancement using Modernizr, and many others.</li>
<li><a href="http://github.com/dcneiner/html5-site-template">HTML5 Site Template</a> by <a href="http://twitter.com/dougneiner">Doug Neiner</a> &#8211; This template is the most simple alternative to the above two templates. It includes the concerns we&#8217;ve addressed in this article, but leaves out some of the extra stuff that you may not need in your web application. If you are overwhelmed with the amount of options from the first two templates, this might be a good place for you to start. Then, if you find yourself in need some of additional features, you can reference the above templates for their implementation.</li>
</ul>

<h2>Conclusion</h2>

<p>Although not all browsers have the same level of support for HTML5, you can still start using many of the syntactical and semantic features that it provides. With a few considerations you can use these features without worrying about backwards compatibility. </p>

<p>As for future blog posts we will look at the following topics:</p>

<ul>
<li>Part 2: Form Enhancements</li>
<li>Part 3: Local &#038; Session Storage</li>
<li>Part 4: Video &#038; Audio Elements</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://enterprisejquery.com/2010/08/enterprise-strategies-for-adopting-html5-part-1-simplified-syntax-semantic-elements/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Create Your First jQuery Plugin Part 2:Plugin Enhancements with .queue and .trigger</title>
		<link>http://enterprisejquery.com/2010/07/create-your-first-jquery-plugin-part-2-revising-your-plugin/</link>
		<comments>http://enterprisejquery.com/2010/07/create-your-first-jquery-plugin-part-2-revising-your-plugin/#comments</comments>
		<pubDate>Thu, 29 Jul 2010 18:06:07 +0000</pubDate>
		<dc:creator>Andrew Wirick</dc:creator>
				<category><![CDATA[Multipart Series]]></category>
		<category><![CDATA[Plugins]]></category>

		<guid isPermaLink="false">http://enterprisejquery.com/?p=144</guid>
		<description><![CDATA[Note: This is part two in a two part series on creating your first plugin. You can find part one here. In the series we&#8217;re creating a plugin to handle displaying, and also queuing a series of a messages. Plugin Enhancements The plugin we worked on in Part 1 focused on getting from a simple [...]
]]></description>
			<content:encoded><![CDATA[<div class="note"><p>Note: This is part two in a two part series on creating your first plugin. You can find part one <a href="http://enterprisejquery.com/2010/07/create-your-first-jquery-plugin-part-1-transition-from-everyday-jquery-code-to-base-plugin/">here</a>. In the series we&#8217;re creating a plugin to handle displaying, and also queuing a series of a messages.</p></div>

<h2>Plugin Enhancements</h2>

<p>The plugin we worked on in Part 1 focused on getting from a simple jQuery snippet to a reusable and scalable plugin. This post will give us an opportunity to look at two popular techniques that can be used in a variety of situations. We&#8217;ll introduce these techniques by adding two enhancements to our code. We will enable the queueing of messages for the message center, and will add features to automatically close the message after a certain time period.</p>

<h3>Utilizing jQuery Queues</h3>

<p>jQuery queues provide an explicit mechanism for running synchronous operations anywhere they might be necessary. Our current plugin is a great fit for queues. If a previous message is being displayed we would prefer that the new message be queued and displayed synchronously afterwards.</p>

<p>The queue portion of the API contains two methods that are used most of the time. <code>.queue</code> is utilized to add items to the queue. It can also be used to determine the number of items currently in a given queue. <code>.dequeue</code> is used to kick off our queue, or at any point move to the next callback in the queue.  <span id="more-144"></span></p>

<p>DOM elements can have an arbitrary number of queues attached to them. Each queue can be identified by using a queue name when using the <code>.queue</code> and <code>.dequeue</code> methods. Internally, jQuery uses a queue on each element with a key <code>fx</code> for animations. You can attach callback functions to this queue as well.</p>

<p>These two JS Bin links (<a href="http://jsbin.com/ofeya3/edit">one</a> and <a href="http://jsbin.com/iyuri3/2/edit">two</a>) provide an introduction to queues and an example of queueing your own custom callbacks in the animation queue. The <a href="http://jsbin.com/ofeya3/edit">first example</a> provides proof of the queueing functionality and shows a typical mistake that is made when combining queued and non-queued operations.  <a href="http://jsbin.com/iyuri3/2/edit">Example two</a> shows leveraging the animation queue with a custom callback to provide more desirable behavior.</p>

<p>It is important to recognize that the developer is directly responsible for controlling the dequeueing of callbacks. When dealing with a custom queue (a queue that is not the <code>fx</code> queue) you must explicitly move the queue to the next callback through the use of <code>.dequeue</code> or another mechanism that we will see in the example.</p>

<p>jQuery uses queueing internally to accomplish animations in a synchronous fashion.</p>

<p>So here&#8217;s what our new code looks like, enhanced with queueing:</p>

<pre class="brush: jscript;">
function ($, undefined) {
  $.fn.myFlashMessage = function (params) {
    // Queue the message for view
    this.queue(&quot;myFlashMessage&quot;, function (next) {
      // Use extend to merge input parameters and defaults.
      // Use an empty object literal first as it is augmented
      // by the extend method.
      var settings = $.extend(
          {},
          {
            levelClass : 'info',
            animationSpeed : 1000
          },
          params);

      if (typeof(settings.message) === 'string') {
        // Now that we are using the jQuery queue method
        // the `this` keyword refers to a single DOM element.
        $(this)
          // Replace html with the message
          .html(settings.message)

          // Add the  appropriate class for the message level
          .addClass(settings.levelClass)

          // Click to close the message.
          // remove the handler once it has run.
          .one(&quot;click&quot;, function () {
            $(this)
              .slideUp(settings.animationSpeed, function(){
                // This will remove the class once slideUp is complete
                $(this).removeClass(settings.levelClass);

                // Next is a function passed in as a parameter
                // to our callback for queue. We can use it to move
                // to the next item in the queue if there is a
                // next function to execute.
                next();
              });
          })
          .slideDown(settings.animationSpeed);
      }
    });

    // Check the length of the queue
    // if the queue length is 1 and the queue
    // is hidden, we need to kick off the queue
    if (this.queue(&quot;myFlashMessage&quot;).length == 1 &amp;&amp; this.is(&quot;:hidden&quot;)) {
      this.dequeue(&quot;myFlashMessage&quot;);
    }
  }
})(jQuery);
</pre>

<p><a href="http://jsbin.com/abide3/138/edit">Live JS Bin Demo</a></p>

<p>A few important features to note in the enhancement:</p>

<ul>
<li>We&#8217;ve put all of our functionality for showing the message inside of a <code>.queue</code> method call. Because our functionality resides within a jQuery method callback function, the value of the keyword &#8216;this&#8217; has changed in our next context. The <code>.queue</code> method will implicitly iterate over our jQuery collection, and the keyword <code>this</code> will now be set to a single DOM element for each function callback.</li>
<li>With <code>.queue</code> the first argument passed in is a function. This function can be used to move to the next callback in the queue by executing the function.  It is conventional to call the function <code>next</code>. Using this function to move to the next callback in the queue is an alternative to explicitly using <code>.dequeue</code>.  This function also has the distinct advantage of the fact that that we don&#8217;t need to know the queue name. In certain cases you may create a callback function that doesn&#8217;t know the name of the queue it will be utilizing.  In this case, using the first argument to move to the next callback in the queue might be your only option.</li>
<li>We have some logic to determine whether we need to jump start the queue. In this case, we can look to see if the message center is hidden and there is only one callback in the queue (the one we just added), then we will need to start (or restart) dequeueing callbacks.</li>
</ul>

<p>There are a few refactors/enhancements that would be good for the example. I encourage you to take the JS Bin example and try the following:</p>

<ul>
<li>Make the plugin more DRY by moving the queue name into a single spot. You could use an explicit variable, or perhaps add on the queue name as a parameter.</li>
<li>This one&#8217;s a bit more challenging: if the queue is already showing, don&#8217;t slide up and then down as a transition. Instead do a quick fade out/fade transition.</li>
</ul>

<p>Keep a queue pattern in mind when looking for solutions to your client-side problems. Other situations may crop up where synchronous operations are paramount. One great example seen in enterprise situations is the need to queue multiple Ajax requests in a certain order to perform a single operation; queues handle this task gracefully.</p>

<h3>Automatically Closing the Message After a Timeout</h3>

<p>A common scenario in client-side development when you want to force an event to fire <em>even</em> if the user has not triggered the event yet. In our case, we want to hide the message after a timeout period even if the user has not clicked on the message. JavaScript provides us with a <code>setTimeout</code> function, which will allow us to run a callback after an interval of of time. jQuery provides us with the awesome power of <code>.trigger</code>, which we can use to force our click event to fire.</p>

<p>One extra thing to consider: when our callback fires after the timeout, the user may have already progressed to a new message.  We don&#8217;t want our callback triggering that message to close. We can solve this problem by storing a unique message id when we go to display our message. We can then look at this message id in our <code>setTimeout</code> callback function to determine if the user is still on the same message.</p>

<p>Our solution:</p>

<pre class="brush: jscript;">
(function ($, undefined) {
  var queueName = 'myFlashMessage';

  $.fn.myFlashMessage = function (params) {
    // Queue the message for view
    this.queue(queueName, function (next) {
      // Use extend to merge input parameters and defaults.
      // Use an empty object literal first as it is augmented
      // by the extend method.
      var settings = $.extend(
          {},
          {
            levelClass : 'info',
            animationSpeed : 1000,
            timeout : 3000
          },
          params),
          messageId = String(+new Date);

      if (typeof(settings.message) === 'string') {
        // Don't repeat initializing a jQuery object
        // we can initialize once since in all methods below
        // the keyword 'this' refers to the same
        // DOM element
        var $this = $(this);

        // Set function to run and close on setTimeout if not already
        setTimeout(function () {
          // We need to make sure that the animation hasn't started,
          // the message isn't hidden, and that the message shown
          // is still the message we intend to close.
          if (!$this.is(&quot;:animated,:hidden&quot;) &amp;&amp;
            $this.data(&quot;messageId&quot;) == messageId) {
            // Now this is just cool.
            $this.trigger(&quot;click&quot;);
          }
        }, settings.timeout);

        $this
          // Add a messageId as metadata on the element
          .data(&quot;messageId&quot;,messageId)
          // Replace html with the message
          .html(settings.message)
          // Add the  appropriate class for the message level
          .addClass(settings.levelClass)
          // Click to close the message.  remove the handler once it has run.
          .one(&quot;click&quot;, function () {
            $this
              .slideUp(settings.animationSpeed, function () {
                // This will remove the class once slideUp is complete
                $this.removeClass(settings.levelClass);

                // Next is a function passed in as a parameter to
                // our callback for queue. We can use it to move to
                // the next item in the queue if there is a next
                // function to execute.
                next();
              });
         })
        .slideDown(settings.animationSpeed);
      }
    });
    // If there are no other messages and the message center
    // is hidden, then we need to kick off the queue.
    if (this.queue(queueName).length === 1 &amp;&amp; this.is(&quot;:hidden&quot;)) {
      this.dequeue(queueName);
    }
  }
})(jQuery);
</pre>

<p><a href="http://jsbin.com/abide3/144/edit">Live JS Bin Demo</a></p>

<p>Two important points to make in this example:</p>

<h4>jQuery&#8217;s .trigger method is just cool</h4>

<p>It is common to see a pattern of setting a callback to run after an interval, and then triggering an event. Since we&#8217;re dealing with the client-side, triggering an event in code is possible. jQuery makes it dead simple.</p>

<h4>Using .data for item metadata</h4>

<p>In our example we store each message id to <code>messageId</code>, passing in a new timestamp as our unique id. If you look into the documentation for <code>.data</code> you&#8217;ll notice that by using the same key every time of <code>messageId</code>, we&#8217;re overwriting the previous <code>messageId</code> stored by the last queued callback.</p>

<p>This snippet from line thirty-two is huge for understanding a key concept in JavaScript: <code>$this.data('messageId') == messageId</code></p>

<p>In JavaScript <em>functions have access to the context in which they were created</em>. In our case, when we created our <code>setTimeout</code> callback, the context included access to <code>messageId</code>, which is the message identifier for the message we were currently queueing up. When the <code>setTimeout</code> callback is executed, we compare that value against <code>$this.data('messageId')</code> which is the currently displayed message identifier.</p>

<p>If you find yourself using <code>setTimeout</code> in bunches, consider using a plugin such as Ben Alman&#8217;s <a href="http://benalman.com/projects/jquery-dotimeout-plugin/">doTimeout</a>.</p>

<p>And there we have it! A modified and scalable plugin. Feel free to extend the plugin as you please, and comment with some JS Bin examples if you find anything interesting or have questions.</p>
]]></content:encoded>
			<wfw:commentRss>http://enterprisejquery.com/2010/07/create-your-first-jquery-plugin-part-2-revising-your-plugin/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Create Your First jQuery Plugin Part 1:Transition From Everyday jQuery Code to Base Plugin</title>
		<link>http://enterprisejquery.com/2010/07/create-your-first-jquery-plugin-part-1-transition-from-everyday-jquery-code-to-base-plugin/</link>
		<comments>http://enterprisejquery.com/2010/07/create-your-first-jquery-plugin-part-1-transition-from-everyday-jquery-code-to-base-plugin/#comments</comments>
		<pubDate>Sat, 17 Jul 2010 16:56:36 +0000</pubDate>
		<dc:creator>Andrew Wirick</dc:creator>
				<category><![CDATA[Multipart Series]]></category>
		<category><![CDATA[Plugins]]></category>

		<guid isPermaLink="false">http://ejq.dev.appendto.com/?p=12</guid>
		<description><![CDATA[Note: This is the first in a two part series on creating your first plugin. In the series, we&#8217;ll create a plugin that will be able to handle displaying and also queuing a series of a messages for the user. Plugin prerequisites: overcoming myths and challenges As a enterprise web developer I often found it [...]
]]></description>
			<content:encoded><![CDATA[<div class="note">

Note: This is the first in a two part series on creating your first plugin. In the series, we&#8217;ll create a plugin that will be able to handle displaying and also queuing a series of a messages for the user.

</div>

<h2>Plugin prerequisites: overcoming myths and challenges</h2>

<p>As a enterprise web developer I often found it challenging to shift my mindset from JavaScript coder towards plugin creator. Not that those opportunities weren&#8217;t there. Rather, I was stifled by a few factors that many enterprise developers face:</p>

<h3>Code ownership and licensing concerns</h3>

<p>Writing software that you are planning to release as open source can often conflict with corporate policies. Given that you are already using jQuery, the organization should already have some understanding of licensing policies. Or, at the very least, the organization has some trust in their developers understanding licensing policies.</p>

<p><span id="more-12"></span>
Publishing plugins under open source licensing is something that most enterprises today should accept. However be sure to do due diligence with your superiors. Some points I would recommend making:</p>

<ul>
<li>Explain to them the power of the open source community. Developers giving back to the community is part of its strength.</li>
<li>jQuery is making you a lot more productive.  Giving back should be part of paying it forward.</li>
<li>Point to plugins you have been able to use in your own development.</li>
<li>Point out that you can garner feedback for your plugin which can help identify bugs and create a better solution for the enterprise.</li>
</ul>

<p>As a worst case, plugins can be used as a pattern and not released as open source.</p>

<h3>The &#8220;plugins are complex&#8221; myth</h3>

<p>&gt; Plugin developers are senior front-end web developers. Any typical plugin is without a doubt something I can never write. Additionally the most useful plugins must be quite complex.</p>

<p>My naivete was quickly broken when I did a little investigation.</p>

<p>Plugins are written by people who want to give back to the community. Newer developers are included in that group.
Many useful plugins are not that complex in code. Some are fairly complex. Here are a few examples from the same developer. These are plugins I have used in code:</p>

<ul>
<li><a href="http://benalman.com/projects/jquery-replacetext-plugin/">Replace Text Plugin</a> &#8211; not terribly complicated.</li>
<li><a href="http://benalman.com/projects/jquery-dotimeout-plugin/">Do Timeout Plugin</a> &#8211; still not complicated.</li>
<li><a href="http://benalman.com/projects/jquery-bbq-plugin/">jQuery BBQ Plugin</a> &#8211; you&#8217;re probably not going to write this one overnight.</li>
</ul>

<p>I&#8217;d assert that all three of these plugins are incredibly useful. Yet only one has a high level of complexity.</p>

<h3>Lack of ability to recognize code that could be a candidate for a plugin</h3>

<p>On your path from a enterprise web coder to developer, this should be one of your goals. Identifying patterns that can be abstracted into plugins are a key to your journey to that &#8216;senior&#8217; level. We&#8217;ll see utility libraries as another possibility for code reuse. But in both cases identifying a pattern is key.</p>

<h2>Starter Code</h2>

<p>Lets get rolling. Here is code I&#8217;ve seen in enterprise code used today. This is an implementation of the incredibly popular &#8220;flash message&#8221; or &#8220;message center&#8221; you see on sites like twitter and stack overflow:</p>

<pre class="brush: jscript;">
$('#flashMessageCenter')
  .html('message for the user')
  .addClass('info')
  .click(function(){
    $(this)
      .slideUp(1000,function(){
        $(this).removeClass('info');
      });
  })
  .slideDown(1000);</pre>

<p><a href="http://jsbin.com/abide3/edit">Live jsbin demo</a></p>

<p>Super. This code seems to work pretty well, and took almost no time to write. The power of the jQuery side of the force&#8230;</p>

<p>This is where the light bulb needs to start going on. What are we doing here? We are displaying messages via some sort of message center for the user. Why not make this into something repeatable?</p>

<h2>Generalizing the Code</h2>

<p>We are going to travel a road to get to the plugin in order to bridge some common knowledge gaps. Lets start with a function that can take in some parameters.</p>

<pre class="brush: jscript;">
var flashMessage = function(message, levelClass, animationSpeed) {
  if(message &amp;&amp; levelClass &amp;&amp; animationSpeed) {
    $('#flashMessageCenter')
      .html(message)
      .addClass(levelClass)
      .click(function(){
        $(this)
          .slideUp(animationSpeed,function(){
            $(this).removeClass(levelClass);
          });
      })
      .slideDown(animationSpeed);
  }
}</pre>

<p>It would be better if we had defaults :</p>

<pre class="brush: jscript;">
var flashMessage = function(message, levelClass, animationSpeed) {
  levelClass = typeof(levelClass) === 'string'
    ? levelClass
    : 'info';
  animationSpeed = typeof(animationSpeed) === 'number'
    ? animationSpeed
    : 1000;
  if(message) {
    $('#flashMessageCenter')
      .html(message)
      .addClass(levelClass)
      .click(function(){
        $(this)
          .slideUp(animationSpeed,function(){
            $(this).removeClass(levelClass);
          });
      })
      .slideDown(animationSpeed);
  }
}</pre>

<p><a href="http://jsbin.com/abide3/2/edit">Live jsbin demo</a></p>

<p>But wait, a bug already! Pay close attention to the <code>.slideUp</code> animation in the demo page. It&#8217;s always fast? Why?</p>

<p>We are attaching a new click handler each time this method is called. What we really want to happen is to attached the handler, let it run once, and then remove it. The next time the flashMessage is called a new handler will be attached with the new set of parameters. Fortunately jQuery gives us a shortcut to do exactly that:</p>

<pre class="brush: jscript;">
var flashMessage = function(message, levelClass, animationSpeed) {
  levelClass = typeof(levelClass) === 'string'
    ? levelClass
    : 'info';
  var animationSpeed = typeof(animationSpeed) === 'number'
    ? animationSpeed
    : 1000;
  if(message) {
    //our message center div id
    $('#flashMessageCenter')
      //replace html with the message
      .html(message)
      //add the appropriate class for the message level
      .addClass(levelClass)
      //click to close the message.
      //remove the handler once it has run.
      .one('click',function(){
        $(this)
          .slideUp(animationSpeed,function(){
          //this will remove the Class
          //once slideUp is complete
            $(this).removeClass(levelClass);
          });
      })
      .slideDown(animationSpeed);
  }
}</pre>

<p>We have a function that we can use to flash messages. But we can spruce this up even more.</p>

<p>I&#8217;m a huge fan of using object literals for parameter inputs. It will allow you to scale out your plugin in the future as thousands of people beg you to expand its functionality.</p>

<p>Again jQuery comes through. This time a utility function is our helper <code>$.extend()</code>. We can use <code>$.extend()</code> to merge an input object literal with a set of default object literals. Awesome!</p>

<pre class="brush: jscript;">
var flashMessage = function(params) {
  //use extend to merge input parameters and defaults.
  //use an empty object literal first as it
  //is overwritten by the extend method.
  var settings = $.extend(
    {},
    {
      levelClass : 'info',
      animationSpeed : 1000
    },
    params);
  if(settings.message) {
    //our message center div id
    $('#flashMessageCenter')
      //replace html with the message
      .html(settings.message)
      //add the appropriate class for the message level
      .addClass(settings.levelClass)
      //click to close the message.
      //remove the handler once it has run.
      .one('click',function(){
        $(this)
          .slideUp(settings.animationSpeed, function(){
            //this will remove the Class
            //once slideUp is complete
            $(this).removeClass(settings.levelClass);
          });
      })
      .slideDown(settings.animationSpeed);
  }
}</pre>

<p><a href="http://jsbin.com/abide3/3/edit">Live jsbin demo</a></p>

<p>Notice that we don&#8217;t specify a message in our default object literal. We expect the user to pass in the message to the function.</p>

<h2>Time for a plugin!</h2>

<p>We are so close. We have a function that can be used. It takes in a sweet object literal. It also does two things that aren&#8217;t so nice:</p>

<ul>
<li>We are polluting the global namespace</li>
<li>We are hard coding our selector for the flash message</li>
</ul>

<p>Lets eliminate both at the same time. And produce our first plugin:</p>

<pre class="brush: jscript;">
(function($,undefined){
  $.fn.myFlashMessage = function(params) {
    //use extend to merge input parameters and defaults.
    //use an empty object literal first as it is
    //overwritten by the extend method.
    var settings = $.extend(
      {},
      {
        levelClass : 'info',
        animationSpeed : 1000
      },
      params);
    if(typeof(settings.message) === 'string') {
      //our jQuery object
      this
        //replace html with the message
        .html(settings.message)
        //add the appropriate class for the message level
        .addClass(settings.levelClass)
        //click to close the message.
        //remove the handler once it has run.
        .one('click',function(){
          $(this)
            .slideUp(settings.animationSpeed, function(){
              //this will remove the Class once
              //slideUp is complete
              $(this).removeClass(settings.levelClass);
            });
        })
       .slideDown(settings.animationSpeed);
    }
  }
})(jQuery);</pre>

<p><a href="http://jsbin.com/abide3/4/edit">Live jsbin demo</a></p>

<h3>A few more topics we just introduced:</h3>

<p>We are using a self invoking anonymous function to create a plugin. That&#8217;s this pattern:</p>

<pre class="brush: jscript;">
(function($, undefined){
...
})(jQuery);
</pre>

<p>The code creates a function without a name (not polluting the global space), and then immediately executes it. There are a few reasons to use this pattern. In our case, we use the function so the we can use the &#8216;$&#8217; to mean &#8216;jQuery&#8217;, even if the &#8216;$&#8217; variable is assigned to something else outside of this function. We also have a parameter &#8216;undefined&#8217;.  Although we aren&#8217;t yet using &#8216;undefined&#8217; in code yet I&#8217;ve added it for future revisions.  Adding &#8216;undefined&#8217; (yet passing in nothing as the parameter when executing the function) allows us to make sure someone didn&#8217;t do this sort of funny business in javascript previous to our function execution:</p>

<pre class="brush: jscript;">
undefined = &quot;I'm defined now!!!&quot;; //legal
</pre>

<p>Next we have the actual assignment of the jQuery plugin:</p>

<pre class="brush: jscript;">
$.fn.myFlashMessage = function(params)
</pre>

<p>This line assures that any future instance of the jQuery object will have access to that method. It&#8217;s a plugin. Nice!</p>

<p>Also looking at the code again I realized I could make a better comparison of the message by making sure it is of a type string.</p>

<p>And there we have it! A complete plugin.</p>

<p>In the next in the plugin post series we are going to continue to expand our plugin, including:</p>

<ul>
<li>Utilize queuing to retrieve and show multiple messages</li>
<li>Automatically close the message center if not clicked in a certain time period</li>
<li>Fix a few quirks we find in the current plugin</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://enterprisejquery.com/2010/07/create-your-first-jquery-plugin-part-1-transition-from-everyday-jquery-code-to-base-plugin/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Enterprise AJAX Patterns Part 1:From Enterprise Beginnings</title>
		<link>http://enterprisejquery.com/2010/07/enterprise-ajax-patterns-part-1-from-enterprise-beginnings/</link>
		<comments>http://enterprisejquery.com/2010/07/enterprise-ajax-patterns-part-1-from-enterprise-beginnings/#comments</comments>
		<pubDate>Sat, 17 Jul 2010 16:55:52 +0000</pubDate>
		<dc:creator>Andrew Wirick</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Multipart Series]]></category>
		<category><![CDATA[Patterns]]></category>

		<guid isPermaLink="false">http://ejq.dev.appendto.com/?p=4</guid>
		<description><![CDATA[jQuery Ajax features provide a slick way to make asynchronous javascript calls from any browser. jQuery even gives us helpers methods to make the calls even simpler. $.get, $.getJSON, $.getScript, $.load, and $.post all give great ways to set up default features and get your ajax calls done quickly. We often see enterprise developers taking [...]
]]></description>
			<content:encoded><![CDATA[<p>jQuery Ajax features provide a slick way to make asynchronous javascript calls from any browser. jQuery even gives us helpers methods to make the calls even simpler. <code>$.get</code>, <code>$.getJSON</code>, <code>$.getScript</code>, <code>$.load</code>, and <code>$.post</code> all give great ways to set up default features and get your ajax calls done quickly.  We often see enterprise developers taking advantage of these shortcut methods for basic Ajax needs.</p>

<p>However, enterprises today require scalable solutions that gracefully handle errors, messages to the user, spinners, and other aspects of a rich user experience.  In these series of posts we are going to step beyond the basic Ajax functionality and build a scalable library solution.   In order to create a functional library you&#8217;ll need to understand the .ajax method and the parameters allowed. If you don&#8217;t already have a handle on .ajax, please visit the <a href="http://api.jquery.com/category/ajax/">extremely useful api site</a> for a quick primer.</p>

<p>For the purpose of these posts we are going to start with a pattern that is often seen in enterprise situations for ajax calls.  In the below example we will attempt to retrieve data from the server with a GET http action via the jQuery.ajax method.  <span id="more-4"></span> The example will show an animated gif to identify loading (hereafter referred to as a spinner).  We will retrieve HTML from the server, and apply that HTML to the DOM using jQuery&#8217;s <code>.html()</code> function.  Finally we will hide our spinner on success or failure of the call by using the complete callback.</p>

<pre class="brush: jscript;">
$('#mySpinnerId').show(); //show my spinner
$.ajax({
    url: 'myUrl',
    dataType: 'html',
    cache: false,
    success: function(myHtml) {
        $('#myHtmlContainer').html(myHtml);
      },
    complete: function() {
        $('#mySpinnerId').hide(); //hide the spinner
      }
  });
</pre>

<p>This functions great for our site, and we decide to move on to another Ajax request.  Our second request:</p>

<pre class="brush: jscript;">
$('#mySpinnerId2').show(); //show my spinner
$.ajax({
    url:      'myOtherUrl',
    cache:    false,
    dataType: 'json',
    success:  function(myJson) {
        // assumes a JSON structure that at least
        // includes {&quot;value&quot;:&quot;someValue&quot;}
        $('#someId').text(myJson.value);  
      },
    complete: function() {
        // hide the spinner
        $('#mySpinnerId2').hide();
      }       
  });
</pre>

<p>Wonderful.  This works as well.  But it is not elegant code.  How do we keep from repeating ourselves?  Is there a better way to set up the loading animations?  How do we handle errors?</p>

<h2>Taking a Step Back</h2>

<p>Before DRYing out this code, lets review the series of callbacks and functionality available to us with jQuery Ajax.</p>

<h3>Ajax Settings (<a href="http://api.jquery.com/jQuery.ajaxSetup/">In API</a>)</h3>

<p><code>.ajaxSetup</code> allow us to set up defaults for any of the parameters available in <code>$.ajax</code>.  In our case, it would make sense to set up caching settings to be default</p>

<h3>Ajax Event Broadcasting</h3>

<p>A <a href="http://docs.jquery.com/Ajax_Events">somewhat obscure documentation page</a> lists out some incredibly important information.  A quick summary:</p>

<h4>Local vs Global Events</h4>

<p>There are some events that are broadcasted for the specific ajax call, and other that are broadcast for any ajax call.  Global event names always have the &#8220;ajax&#8221; prefix on the name.  Local events do not.</p>

<h4>Order of event broadcasting</h4>

<p>There is a rich set of events that we can tap into for any of our ajax needs.  In particular, we have events that will fire on any error, as well as firing on the completion of code.</p>

<p>Given that information, lets create an object that will handle a few things: 1) showing/hiding spinners 2) setting up defaults that are specific to our website.</p>

<pre class="brush: jscript;">
var mySiteAjax = (function($){
  return {
    getViaAjax: function(params){
      var settings = $.extend({
        url:      '', 
        spinner:  undefined, 
        dataType: 'html',
        cache:    false,
        success:  function(){}
      }, params);

      $.ajax({
          beforeSend: function(){ 
            $(settings.spinner).show();
          },
          url:        settings.url,
          dataType:   settings.dataType,
          success:    settings.success,
          complete:   function(){
              $(settings.spinner).hide();
            }      
        });
    } 
  };
})(jQuery);
</pre>

<p>Your response might be &#8220;I thought you were creating an object?  What is all of this?&#8221;  Lets cover it in pieces:</p>

<p><strong>Self executing (invoking) anonymous functions</strong></p>

<pre class="brush: jscript;">
function($){
  ...
})(jQuery);
</pre>

<p>This pattern is a well known one in javascript.  This pattern allows us to create a function without a name (anonymously so that we don&#8217;t pollute the global scope), and then immediately execute it.  Specifically we are using the pattern so that we can accept jQuery as a parameter to a function, but use the variable &#8216;$&#8217; internally in the function.  This allows us to ensure that if any third party library were attached and this code was in a library attached afterwards, it would still behave as expected.</p>

<p><strong>jQuery.extend()</strong></p>

<p><code>$.extend</code> is another piece of jQuery beauty that allows us to set up default parameters very easily.</p>

<p><strong><code>return</code> object literal</strong></p>

<p>Note that we are creating an function and then immediately executing that function.  Thus whatever is returned by the function will be assigned to <code>mySiteAjax</code>.  In this case, it is an object literal which includes a single function &#8211; <code>getViaAjax</code>.</p>

<h2>Usage</h2>

<p>Given our two example above, here is the usage:</p>

<h3>Example 1:</h3>

<pre class="brush: jscript;">
mySiteAjax.getViaAjax({
  spinner : '#mySpinnerId',
  url : 'myUrl',
  success : function(myHtml){
      $('#myHtmlContainer').html(myHtml);
    }
});
</pre>

<h3>Example 2:</h3>

<pre class="brush: jscript;">
mySiteAjax.getViaAjax({
  spinner : '#mySpinnerId',
  url : 'myUrl',
  dataType: 'json',
  success : function(myJson){
      $('#someId').text(myJson.value);  
    }
});
</pre>

<p>We&#8217;ve saved ourselves some code.  But more importantly, we&#8217;ve started down the path of creating a library that can handle all of our site&#8217;s ajax needs in an elegant manner.  </p>

<p>Over this series, we will continue to expand our <code>mySiteAjax</code> object to include more behavior.  Next up, we&#8217;ll cover a error handling strategy.</p>

<ul>
<li>Part 2: Handling errors and global loading animations</li>
<li>Part 3: JSON wrapper</li>
<li>Part 4: Putting it all together</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://enterprisejquery.com/2010/07/enterprise-ajax-patterns-part-1-from-enterprise-beginnings/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using apc
Page Caching using apc
Database Caching 7/15 queries in 0.003 seconds using apc
Content Delivery Network via ejq.a2cdn.net

Served from: enterprisejquery.com @ 2012-02-05 12:53:18 -->
