<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Enterprise jQuery</title>
	
	<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" />		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/EnterpriseJquery" /><feedburner:info uri="enterprisejquery" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><creativeCommons:license>http://creativecommons.org/licenses/by-nd/3.0/</creativeCommons:license><feedburner:emailServiceId>EnterpriseJquery</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>How Good C# Habits can Encourage Bad JavaScript Habits:Part 3 – Function Scope, Hoisting, &amp; Closures</title>
		<link>http://feedproxy.google.com/~r/EnterpriseJquery/~3/kssHKUxQB-I/</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>
<img src="http://feeds.feedburner.com/~r/EnterpriseJquery/~4/kssHKUxQB-I" height="1" width="1"/>]]></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>
		<feedburner:origLink>http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-3/</feedburner:origLink></item>
		<item>
		<title>How Good C# Habits can Encourage Bad JavaScript Habits:Part 2 – False-y, Testing and Default Values, Comparisons, and Looping</title>
		<link>http://feedproxy.google.com/~r/EnterpriseJquery/~3/tWsKN_bGW2Q/</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>
<img src="http://feeds.feedburner.com/~r/EnterpriseJquery/~4/tWsKN_bGW2Q" height="1" width="1"/>]]></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>
		<feedburner:origLink>http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2/</feedburner:origLink></item>
		<item>
		<title>How Good C# Habits can Encourage Bad JavaScript Habits:Part 1</title>
		<link>http://feedproxy.google.com/~r/EnterpriseJquery/~3/_3A1NaQ4B0w/</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>
<img src="http://feeds.feedburner.com/~r/EnterpriseJquery/~4/_3A1NaQ4B0w" height="1" width="1"/>]]></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>
		<feedburner:origLink>http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/</feedburner:origLink></item>
		<item>
		<title>Creating an Ajax Component:Handling Errors and Loading Notifications with Publish and Subscribe</title>
		<link>http://feedproxy.google.com/~r/EnterpriseJquery/~3/dsVYPZIY-QY/</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>
<img src="http://feeds.feedburner.com/~r/EnterpriseJquery/~4/dsVYPZIY-QY" height="1" width="1"/>]]></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>
		<feedburner:origLink>http://enterprisejquery.com/2010/09/creating-an-ajax-component-handling-errors-and-loading-notifications-with-publish-and-subscribe/</feedburner:origLink></item>
		<item>
		<title>Enterprise jQuery Manifesto</title>
		<link>http://feedproxy.google.com/~r/EnterpriseJquery/~3/uICr3OKAK1w/</link>
		<comments>http://enterprisejquery.com/2010/08/enterprise-jquery-manifesto/#comments</comments>
		<pubDate>Fri, 20 Aug 2010 16:10:47 +0000</pubDate>
		<dc:creator>Jonathan Sharp</dc:creator>
				<category><![CDATA[Industry]]></category>
		<category><![CDATA[goals]]></category>
		<category><![CDATA[overview]]></category>
		<category><![CDATA[strategy]]></category>

		<guid isPermaLink="false">http://enterprisejquery.com/?p=509</guid>
		<description><![CDATA[EnterprisejQuery.com is run by appendTo. appendTo launched in October of 2009 with Mike Hostetler and myself having the vision of providing enterprise grade services for jQuery. Both of us have a long history of experience in the large enterprise as well as startups. We’ve worked in the trenches and have seen first hand the challenges [...]
]]></description>
			<content:encoded><![CDATA[<p><strong>EnterprisejQuery.com is run by <a href="http://appendto.com">appendTo</a>.</strong> </p>

<p>appendTo launched in October of 2009 with Mike Hostetler and myself having the vision of providing enterprise grade services for jQuery. Both of us have a long history of experience in the large enterprise as well as startups. We’ve worked in the trenches and have seen first hand the challenges that organizations face. </p>

<p>appendTo has a diverse set of enterprise experience with the 7 additional employees we’ve hired: Levi DeHaan, Scott González, Elijah Manor, Doug Neiner, Andrew Powell, Leah Silber, and Andrew Wirick. Of which we&#8217;ve worked at, contracted for, and consulted with several large organizations such as: AOL, Apple, Blue Cross Blue Shield (NE), BMW, Bureau of Land Management (BLM), Chrysler, CSC (Computer Sciences Corporation), Ford, GM, Guardian Life, IBM, Microsoft, Motorola, National Instruments, National Renewable Energy Lab (NREL), Union Pacific Railroad, Xcel Energy, and Zurich International.</p>

<p>Every organization is different, but core themes naturally emerge. In July of this year, appendTo launched EnterprisejQuery.com to cater to <em>this</em> audience and it has sparked a debate about “what is the enterprise” and “does jQuery fit in the enterprise”.<span id="more-509"></span></p>

<h2>What is the Enterprise?</h2>

<p>So far, there have been a number of definitions of “what the enterprise is” and while they make a good attempt, they&#8217;re too focused. The point missing from the discussion thus far is that the enterprise is comprehensive and cross discipline. It’s not solely large applications or large teams, it&#8217;s any company that is using it&#8217;s resources (people, time and money) to build applications and tools for the desktop, web and/or mobile platforms. </p>

<p>The intended audiences of these applications vary drastically between companies with some corporations developing almost exclusively for an internal audience. These organizations traditionally have multiple stakeholders and development decisions encompass varying agendas and goals. This is why EnterprisejQuery.com covers and will continue to cover basic and advanced jQuery techniques.</p>

<h2>Does jQuery have a place in the Enterprise?</h2>

<p>A little more background first. jQuery has seen adoption in the enterprise since its first release. Initially it was a grassroots movement with developers adopting jQuery because it solved their problems. It’s important to point out that these problems were (and continue to be) integration focused. Enterprise already had (and has) existing tools and architectures in place. Then starting in 2008, the next change took place in which the jQuery movement shifted from grassroots to corporate policy. jQuery gained critical mass to the point in which management became aware of the need to standardize, as many did and did so with jQuery. </p>

<p>So what about some of the technical challenges presented such as code organization, best practices, and large scale projects? jQuery fits in the enterprise stack well, even in large applications, in that it does not preclude finding the right solutions to these problems. jQuery fits the needs for all of these because it integrates as you see fit. One question was raised as to why you need jQuery with additional components to integrate and saw it as a weakness, making an argument that jQuery should provide the entire “stack”. </p>

<p>It’s a fundamental philosophical difference in that jQuery is focused on doing the best at a core competency. Just like in a *nix environment you can take a series of discrete tools and chain them together via pipes. It integrates however your environment is established. If a library requires too many changes to adopt, it becomes a greater risk than a help to the enterprise. Our vision is to build and endorse tools that are loosely coupled and can be integrated into an existing enterprise solution.</p>

<p>So where is jQuery and the Enterprise at today? jQuery is deeply embedded in projects, applications and the culture of the enterprise. It fills a need and solves the problems that developers face in a non-overbearing way. It provides a consistent goal and approach in leading an organization’s development strategy. It does just enough, and leaves the rest up to the developer.</p>

<h2>What to expect from EnterprisejQuery.com</h2>

<p>EnterprisejQuery.com seeks to cover enterprise topics comprehensively. Though not all enterprise users have large front-end application concerns, we intend to address those topics. Many have more basic concerns and we mean to address those as well. This is why some posts you’ll walk away saying “I knew that!” and others you’ll have to read multiple times. As the amount of site content grows, we will make it easier for you to discern as an enterprise user which material suits your current needs.</p>

<p>So in summary, jQuery is in the enterprise, it has been and will continue making an impact. Enterprises differ greatly, and cover a wide spectrum of disciplines. We will be addressing this space comprehensively. Is there a topic your facing that you&#8217;d like to see covered? Drop us an e-mail at <a href="mailto:enterprise-jquery@appendto.com">enterprise-jquery@appendto.com</a>.</p>
<img src="http://feeds.feedburner.com/~r/EnterpriseJquery/~4/uICr3OKAK1w" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://enterprisejquery.com/2010/08/enterprise-jquery-manifesto/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<feedburner:origLink>http://enterprisejquery.com/2010/08/enterprise-jquery-manifesto/</feedburner:origLink></item>
		<item>
		<title>Enterprise Strategies for Adopting HTML5 Part 1:Simplified Syntax &amp; Semantic Elements</title>
		<link>http://feedproxy.google.com/~r/EnterpriseJquery/~3/8iO4iw3_dVU/</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>
<img src="http://feeds.feedburner.com/~r/EnterpriseJquery/~4/8iO4iw3_dVU" height="1" width="1"/>]]></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>
		<feedburner:origLink>http://enterprisejquery.com/2010/08/enterprise-strategies-for-adopting-html5-part-1-simplified-syntax-semantic-elements/</feedburner:origLink></item>
		<item>
		<title>Javascript Parameter Patterns with $.extend and Beyond</title>
		<link>http://feedproxy.google.com/~r/EnterpriseJquery/~3/_ykOvBlXNCw/</link>
		<comments>http://enterprisejquery.com/2010/08/javascript-parameter-patterns-with-extend-and-beyond/#comments</comments>
		<pubDate>Thu, 12 Aug 2010 17:06:54 +0000</pubDate>
		<dc:creator>Andrew Wirick</dc:creator>
				<category><![CDATA[Patterns]]></category>

		<guid isPermaLink="false">http://enterprisejquery.com/?p=269</guid>
		<description><![CDATA[Enterprise developers have a tendency to misunderstand JavaScript&#8217;s function parameters. When getting started, many expect JavaScript functions to work much like the server-side languages they&#8217;re already familiar with. There can then be a fair bit of confusion when they find out things work a little differently with JavaScript. The languages generally used on the server-side of [...]
]]></description>
			<content:encoded><![CDATA[<p>Enterprise developers have a tendency to misunderstand JavaScript&#8217;s function parameters. When getting started, many expect JavaScript functions to work much like the server-side languages they&#8217;re already familiar with. There can then be a fair bit of confusion when they find out things work a <em>little</em> differently with JavaScript.</p>

<p>The languages generally used on the server-side of enterprise development have static typing. The number and type of each parameter must be declared. In contrast JavaScript is considered a language with dynamic typing.  JavaScript parameters do not have to be tied to a specific type at compile time. Additionally server-side languages do not include any of the &#8216;free&#8217; parameters we get in JavaScript (more discussion on these parameters below).</p>

<p>A great example of the gap between common server-side languages and JavaScript is the <code>.each</code> method.  To use this method you supply a function which will be executed against each element within the jQuery wrapped collection.</p>

<p>My first encounter with <code>.each</code> was similar to this:</p>

<pre class="brush: jscript;">
//...
// note: this example is archaic as of 1.4 release
// please use function callback with .text instead!
$('.someClass').each(function() {
  var $this = $(this);
  $this.text($this.text() + &quot; some extra text&quot;);
});
//...
$('.someClass').each(function(idx,val) {
  if(!(idx % 3)) { //modulus : will be true
                        //on every third element
    $(val).somejQueryMethod();
  }
});
//...
</pre>

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

<p><span id="more-269"></span>
In my first encounter with this code I stared with a combination of wonder and horror. How are there two anonymous functions that each have different number of parameters?  How could jQuery possibly invoke each of these functions successfully?</p>

<p>The secret isn&#8217;t jQuery&#8217;s.  These snippets work because of the way JavaScript handles parameters.</p>

<p>In this post we are going to take a look at some of the language semantics for functions parameters.  We&#8217;ll then use that knowledge to come up with a parameter passing pattern that is incredibly useful and expressive.</p>

<h2>Javascript Function Parameters</h2>

<p>There is an incredible amount of freedom in parameter passing in JavaScript. This flexibility comes from a few key concepts regarding JavaScript function parameters:</p>

<h3>Declaring and passing parameters is optional in JavaScript</h3>

<p>I could declare a function with five named parameters but the caller of that function does not have to pass in any parameters.  Conversely I could declare a function with zero named parameters and the caller could pass in five when invoking the function.</p>

<pre class="brush: jscript;">
var myFunction1 = function(param1, param2, param3) {
  // ...
};

myFunction1();
// myFunction1 will execute when invoke, even though
// there is a parameter mistmatch

var myFunction2 = function() {
// ...
};

myFunction2(&quot;here&quot;, &quot;are&quot;, &quot;some&quot;, &quot;parameters&quot;);
// myFunction2 will execute when invoked even though there
// are no named parameters in the function declaration
</pre>

<p><a href="http://jsbin.com/ewiyi3/2/edit">JS Bin Demo</a></p>

<h3>Every function includes an arguments array-like object as a parameter</h3>

<p>You actually never have to declare parameters when declaring a function in JavaScript.  Arguments passed in during function invocation will all be stored in a variable with the keyword <code>arguments</code>.  <code>arguments</code> is an array-like object which you can use to retrieve and use all parameters in the order they were passed in.  You could use this array to utilize an indefinite number of parameters:</p>

<pre class="brush: jscript;">
var myAdder = function(){
  var i = 0, result = 0;
  //we can check to see if the object in the arguments
  //'array' exists. we also check the type of the input
  while(arguments[i] &amp;&amp; typeof arguments[i] === 'number' ) {
    //add it and continue
    result += arguments[i];
    i++;
  }
  return result;
}

myAdder(1,2,3,4,5); //15
</pre>

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

<h3>Every function also gets a parameter with the keyword &#8216;this&#8217;</h3>

<p>We are not going into the details of the <code>this</code> operator in this post.  It is sufficient to know that the <code>this</code> operator exists and its meaning depends on how the function is invoked.</p>

<h3>Parameters can be any type when passed in to a function</h3>

<p>The caller of a function could pass in any type for your parameters.  For example, if you have a function which expects a single parameter the caller may choose to pass in:
    * nothing (would be undefined in your function)
    * a function object
    * a string
    * a number
    * any other object
It is the responsibility of the function to detect and react to these different types.  That may seem a bit too loose at first.  Yet it opens up incredible expressiveness that allows jQuery to do much of the magic it performs today.</p>

<p>Consider when we use the <code>jQuery</code> (or the alias <code>$</code>) function with one parameter.  This core piece of jQuery acts radically different depending on what we specify as the first argument when invoking the function. Here are three examples of passing in different types of objects to the jQuery function and how the function behaves:</p>

<pre class="brush: jscript;">
$('.myClass li')
// here the jQuery function will determine
// that the first argument is a string.  It will
// use the selector engine (sizzle) to determine
// which DOM elements fit the selector, and
// will return a jQuery object with a collection
// of those dom elements
</pre>

<pre class="brush: jscript;">
$(document);
// jQuery recognizes that we have passed
// in a DOM Element.  The library returns
// a jQuery object with the collection of 1
// element - the DOM element.
</pre>

<pre class="brush: jscript;">
$(function(){
  //...
});
// jQuery recognizes that we have passed
// in a function.  It binds the function to
// be fired when the DOM is ready
// this code results in the same behavior as
// using $(document).ready(function(){...
</pre>

<p>This isn&#8217;t function overloading. JavaScript has no function overloading in the traditional sense.  Yet jQuery radically changes behavior based on the type of our input parameters.</p>

<h2>Parameter Strategy: Object Literals</h2>

<p>A typical starting point when creating named functions in JavaScript is trying to use a list of parameters.  This approach feels familiar to creating functions in statically typed languages. Yet challenges are immediately hit when using a series of named parameters. If the bulk of your arguments are optional you can run into nearly insurmountable issues:</p>

<pre class="brush: jscript;">
var myUtilityFunction = function(arg1, arg2, arg3) {
  //how do we make argument1 or argument2 optional?
};
</pre>

<p>This pattern can work for methods were you have a few parameters and all of them are required.  Anytime you extend the function though it becomes more difficult to manage optional parameters.  If all of the arguments are the same type it may be impossible to have certain arguments be optional.</p>

<p>A much better pattern would be to pass in a single object literal.  In that case we can always look for the specific parameters by name within the object passed in and take action if the object property does not exist:</p>

<pre class="brush: jscript;">
var myUtilityFunction = function(args){
  // this statement is called a ternary statement
  // the first portion is a condition. if the
  // condition evaluates to  true, the next portion (after
  // the question mark) will run.  Otherwise the
  // second statement (after the colon) will run
  var param1 = args &amp;&amp; args.param1 !== undefined
    ? args.param1
    : &quot;my default 1&quot;;
  var param2 = args &amp;&amp; args.param2 !== undefined
    ? args.param2
    : &quot;my default 2&quot;;
  // ...
};
//...
//usage
myUtilityFunction({
  param1 : &quot;my first param&quot;,
  param2 : &quot;my second param&quot;
});
</pre>

<p>While this pattern is functional we have repeating checking of each parameter. As this function grows our parameter checking would become even uglier. A better solution would be to have a default object literal to merge with the object literal passed in by the caller.</p>

<h2>Using Extend to Merge Object Literals</h2>

<p>As usual, jQuery provides a great feature to allow us to take object literals and combine them with our defined inline defaults. <code>jQuery.extend</code> takes in any number of objects and combines them into a single object.  In our case we will use <code>jQuery.extend</code> to merge a default object literal with the parameter object:</p>

<pre class="brush: jscript;">
var myFunction = function(args) {
  var parameters = $.extend(true, {default1: 'hello',
    default2: 'world'},args);
};
</pre>

<p><a href="http://jsbin.com/epixo3/edit">JS Bin demo with Usage</a></p>

<p>In this example the first parameter lets extend know to do a deep copy of all of the objects.</p>

<p>This provides us with a great solution. If your function can run entirely on defaults then the caller doesn&#8217;t have to pass in anything. Additionally we can scale our function by adding extra parameters with defaults which will not break any current code or add additional checks!</p>

<h2>Allowing Arbitrary Number of Object Literals</h2>

<div class="note">

If you have made it this far then congratulations!  The above pattern provides a wonderful practice that can be used in many cases when designing functions.  We are going to try and take the pattern one extra step.  The JavaScript involved in this solution is more advanced.  It may be confusing at first.  I highly encourage you to read it, play with the examples, and ask any questions you have in the comments.

</div>

<p>There are reasons that the caller of our function may have multiple object literals they would like to pass in to our function.  For example the calling function may have defaults and passed in parameters. With our current solution, the caller would need to combine those multiple objects using <code>jQuery.extend</code>, and then call our function, which again uses <code>jQuery.extend</code>.</p>

<p>Recall that JavaScript methods can use any number of parameters.  If we use the our <code>arguments</code> variable that we get for free with each function, we should be able to combine many object literals together.  But how can we use <code>jQuery.extend</code> and the method our own <code>arguments</code> object?  An attempt to use <code>jQuery.extend</code> and just passing in our <code>arguments</code> object will not give us our intended behavior:</p>

<pre class="brush: jscript;">
var myFunction function(){
  var parameters = $.extend.apply(true, arguments);
  // parameters == ?
  // $.extend with only a single object as in this
  // example has special meaning. I encourage
  // you to investigate. But it is not what we want
  // in our case.
};
</pre>

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

<p>JavaScript provides us with a solution. <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Function/apply"><code>apply</code></a> is a method that is available on any function. The first parameter of <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Function/apply"><code>apply</code></a> is what the keyword <code>this</code> should reference when the function is invoked.  The second parameter is an array (or array-like) of the parameters the function will receive in <code>arguments</code>.  <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Function/apply"><code>apply</code></a> is letting us set up the conditions around which a function is invoked.</p>

<p>In our case we can use <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Function/apply"><code>apply</code></a> to set the <code>arguments</code> object of <code>jQuery.extend</code> to be the arguments passed in by our caller:</p>

<pre class="brush: jscript;">
var myFunc = function() {
  // the apply invocation pattern allows us to
  // pass arguments directly on to the jQuery.extend
  // method.  The first parameter is what the 'this'
  // keyword will be set to in the function
  // the second parameter will set the arguments
  // for the function
var options = $.extend.apply( null, arguments );
  // ..
  }
}
</pre>

<p><a href="http://jsbin.com/oqemu/5/edit">JS Bin Demo with Usage</a></p>

<p>We are close but we are missing our deep copy for <code>jQuery.extend</code> and our defaults.  Since <code>arguments</code> is not a true array we can&#8217;t do simple concatenation and add true and our default object as the first two parameters.  However we can turn the <code>arguments</code> into an array and then concatenate with our extra parameters:</p>

<pre class="brush: jscript;">
var myFunc = function() {
  // we can use Array's native slice method to
  // 'convert' the arguments in to a true array
  var args = Array.prototype.slice.call(arguments, 0),
        defaults  = {
          // ...
        },
  // the apply invocation pattern allows us to
  // pass arguments directly on to the jQuery.extend
  // method.  The first parameter is what the 'this'
  // keyword will be set to in the function
  // the second parameter will set the arguments
  // for the function
  options = $.extend.apply( null, [true, defaults].concat(args) );
  // ...
}
</pre>

<p><a href="http://jsbin.com/ikito3/3/edit">JS Bin Demo with Usage</a></p>

<p><a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/slice"><code>Array.prototype.slice</code></a> allows us to return a true array from our <code>arguments</code> object.  We can then create a new array which only includes <code>true</code> and our defaults and then concatenate our arguments on to that new array.  We then pass that array in as the arguments for <code>jQuery.extend</code>.</p>

<p>The idea for this solution came from <a href="http://twitter.com/scott_gonzalez">@scott_gonzalez</a> and the jQuery UI team. You can see their implementation of this solution on <a href="http://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.widget.js#L78">this jQuery UI GitHub page</a>.  The difference in their solution is that they are accounting for the first parameter possibly being a string and not part of the object literals. jQuery UI&#8217;s use of this pattern also means that you can pass in any number of object literals to a jQueryUI method (like <a href="http://jqueryui.com/demos/draggable/"><code>draggable()</code></a> or <a href="http://jqueryui.com/demos/datepicker/"><code>datePicker()</code></a> ) and the merging will be completed for you.</p>

<p>We now have a great pattern that is extremely flexible.  Any number of object literals can come from the caller and we can easily merge them in one place. We can also merge in our default parameters. New parameters with defaults can be added without breaking any caller code.  </p>

<p>It feels good to use the powerful parts of a language.</p>
<img src="http://feeds.feedburner.com/~r/EnterpriseJquery/~4/_ykOvBlXNCw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://enterprisejquery.com/2010/08/javascript-parameter-patterns-with-extend-and-beyond/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		<feedburner:origLink>http://enterprisejquery.com/2010/08/javascript-parameter-patterns-with-extend-and-beyond/</feedburner:origLink></item>
		<item>
		<title>Create Your First jQuery Plugin Part 2:Plugin Enhancements with .queue and .trigger</title>
		<link>http://feedproxy.google.com/~r/EnterpriseJquery/~3/iDHTxAV8GDg/</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>
<img src="http://feeds.feedburner.com/~r/EnterpriseJquery/~4/iDHTxAV8GDg" height="1" width="1"/>]]></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>
		<feedburner:origLink>http://enterprisejquery.com/2010/07/create-your-first-jquery-plugin-part-2-revising-your-plugin/</feedburner:origLink></item>
		<item>
		<title>Mock Your Ajax Requests with Mockjax for Rapid Development</title>
		<link>http://feedproxy.google.com/~r/EnterpriseJquery/~3/A0wmPXjiXMs/</link>
		<comments>http://enterprisejquery.com/2010/07/mock-your-ajax-requests-with-mockjax-for-rapid-development/#comments</comments>
		<pubDate>Thu, 22 Jul 2010 08:00:38 +0000</pubDate>
		<dc:creator>Jonathan Sharp</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[Plugins]]></category>

		<guid isPermaLink="false">http://enterprisejquery.com/?p=106</guid>
		<description><![CDATA[Most backend developers are familiar with the concepts of mocking objects or stubbing in methods for unit testing. For those not familiar with mocking, it&#8217;s the simulation of an interface or API for testing or integration development purposes. Mocking with front-end development though is still quite new. Much of the development that appendTo does focuses [...]
]]></description>
			<content:encoded><![CDATA[<p>Most backend developers are familiar with the concepts of <a href="http://en.wikipedia.org/wiki/Mock_object">mocking objects</a> or stubbing in methods for unit testing. For those not familiar with mocking, it&#8217;s the simulation of an interface or API for testing or integration development purposes. Mocking with front-end development though is still quite new.</p>

<p>Much of the development that <a href="http://appendto.com">appendTo</a> does focuses on front-end development tied to <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">RESTFUL</a> web services. <strong>As such we&#8217;re able to spec out the service contract and data format at the beginning of a project and develop the front-end interface against mock data while the back end team builds the production services.</strong></p>

<p>I originally developed this plugin for appendTo back in March of this year and our <a href="http://twitter.com/appendto/team">team</a> has been using it in all of our projects since. appendTo is committed to sharing our tools and best practices with the community so it&#8217;s with much excitement that we&#8217;re releasing this plugin. (A sneak peek was available to the Silicon Valley JavaScript Users Group and those that attended our OSCON tutorial)</p>

<h2>Plugin Overview</h2>

<p><strong>Abstract:</strong> The mockjax plugin is a development and testing tool for intercepting and simulating ajax requests made with jQuery with a minimal impact on changes to production code.</p>

<ul>
<li><strong>Project Home:</strong> <a href="http://github.com/appendto/jquery-mockjax">http://github.com/appendto/jquery-mockjax</a></li>
<li><strong>Raw Source:</strong> <a href="http://github.com/appendto/jquery-mockjax/raw/master/jquery.mockjax.js">http://github.com/appendto/jquery-mockjax/raw/master/jquery.mockjax.js</a></li>
<li><strong>Issue Tracking:</strong> <a href="http://github.com/appendto/jquery-mockjax/issues">http://github.com/appendto/jquery-mockjax/issues</a>
<span id="more-106"></span></li>
</ul>

<h2>Overview: Your First Mock</h2>

<p>Our first example will be for a simple REST service for a fortune app with the REST endpoint being <code>/restful/fortune</code> which returns the following JSON message:</p>

<pre class="brush: jscript;">
{ &quot;status&quot;: &quot;success&quot;,
  &quot;fortune&quot; : &quot;Are you a turtle?&quot;
}
</pre>

<p>To pull the fortune into our page, we&#8217;d use the following HTML &#038; jQuery code:
<pre class="brush: xml;">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Fortune App&lt;/title&gt;
    &lt;script src=&quot;http://code.jquery.com/jquery-1.4.2.min.js&quot;&gt;&lt;/script&gt;
  &lt;/head&gt;
&lt;body&gt;
  &lt;div id=&quot;fortune&quot;&gt;&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre></p>

<pre class="brush: jscript;">
$.getJSON('/restful/fortune', function(response) {
  if ( response.status == 'success') {
    $('#fortune').html( 'Your fortune is: ' + response.fortune );
  } else {
    $('#fortune').html( 'Things do not look good, no fortune was told' );
  }
});
</pre>

<p>At this point if we were to run this code it would fail since the REST service has yet to be implemented. This is where the benefit of the Mockjax Plugin starts to pay off. The first step in using Mockjax is to include the Plugin (you can grab the latest source from <a href="http://github.com/appendto/jquery-mockjax/raw/master/jquery.mockjax.js">github</a>) Once you have that included, you can start intercepting Ajax requests and mocking the responses. So let&#8217;s mock out the service by including the following code:</p>

<pre class="brush: jscript;">
$.mockjax({
  url: '/restful/fortune',
  responseTime: 750,
  responseText: {
    status: 'success',
    fortune: 'Are you a turtle?'
  }
});
</pre>

<p><strong>Defining a JOSN string inline requires a <code>JSON.stringify</code> method to be available. For some browsers you may need to include <a href="http://json.org/json2.js">json2.js</a></strong></p>

<p>What the plugin does at this point is replace the <code>$.ajax</code> method with a wrapper that transparently checks the URL being requested. If the URL matches one defined by <code>$.mockjax()</code>, the plugin intercepts the request and sets up a mock <code>XMLHttpRequest</code> object before executing the <code>jQuery.ajax</code> handler. Otherwise, the request is handed back to the native <code>$.ajax</code> method for normal execution. One benefit in this implementation detail is by simulating the <code>XMLHttpRequest</code> object, the plugin continues to make use of jQuery&#8217;s native ajax handling.</p>

<p>As you write code to mock responses, there&#8217;s great value in there are no modifications required to production code. The mocks can be transparently inserted. This provides easy integration into most frameworks by including the plugin and mock definitions through your build framework. It&#8217;s also possible to include it at run time by listening for a flag query string flag and injecting the plugin and definitions.</p>

<h2>Mockjax in Depth</h2>

<p>Now let&#8217;s look at the various approaches to defining mocks as offered by the plugin. The sections below feature an extensive overview of the flexibility in Mockjax and creating responses.</p>

<h2>Data Types Available for Mocking</h2>

<p>jQuery is able to handle and parse <code>Text</code>, <code>HTML</code>, <code>JSON</code>, <code>JSONP</code>, <code>Script</code> and <code>XML</code> data formats and Mockjax is able to mock any of those formats. Two things to note, depending upon how you Mock out <code>JSON</code> and <code>JSONP</code> you may need to include <a href="http://json.org/json2.js">json2.js</a> for the <code>JSON.stringify()</code> method. Additionally if you mock XML inline, you&#8217;ll need to include the <a href="http://github.com/appendto/jquery-xmldom"><code>xmlDOM</code></a> plugin that transforms a string of XML into a DOM object. If you use the proxy approach outlined below, there&#8217;s no need to include either the JSON or XMLDOM plugins.</p>

<h2>Step 1. Define the URL</h2>

<p>The first thing you need to do when mocking a request is define the URL end-point to intercept and mock. As with our example above this can be a simple string:</p>

<pre class="brush: jscript;">
$.mockjax({
  url: '/url/to/rest-service'
});
</pre>

<p>or contain a <code>*</code> as a wildcard:</p>

<pre class="brush: jscript;">
$.mockjax({
  // Matches /data/quote, /data/tweet etc.
  url: '/data/*'
});
</pre>

<p>or a full regular expression:</p>

<pre class="brush: jscript;">
$.mockjax({
  // Matches /data/quote, /data/tweet but not /data/quotes
  url: /^\/data\/(quote|tweet)$/i
});
</pre>

<h2>Step 2. Define the Response</h2>

<p>The second step is to define the type of response. The two main properties you&#8217;ll be dealing with are either <code>responseText</code> or <code>responseXML</code>. These properties mirror the native <code>XMLHttpRequest</code> object properties that are set during a live response. There are three different patterns for specifying the responses: Inline, Proxy, and Callback.</p>

<h3>Inline Responses</h3>

<p>A simple text response would be:</p>

<pre class="brush: jscript;">
$.mockjax({
  url: '/restful/api',
  responseText: 'A text response from the server'
});
</pre>

<p>A simple XML response would be:</p>

<pre class="brush: jscript;">
$.mockjax({
  url: '/restful/api',
  // Need to include the xmlDOM plugin to have this translated into a DOM
  responseXML: '&lt;document&gt;&lt;quote&gt;Hello world!&lt;/quote&gt;&lt;/document&gt;'
});
</pre>

<p>As you can quickly see, if you have a significant amount of data being mocked this becomes unwieldy. So that brings us to the next pattern of proxying.</p>

<h3>Proxy</h3>

<p>In this example below, the Mockjax plugin will intercept requests for <code>/restful/api</code> and redirect them to <code>/mocks/data.json</code>. </p>

<pre class="brush: jscript;">
$.mockjax({
  url: '/restful/api',
  proxy: '/mocks/data.json'
});
</pre>

<h3>Callback</h3>

<p>In the final response pattern, we can define a callback on the <code>response</code> property and have it set <code>responseText</code> or <code>responseXML</code> as needed.</p>

<pre class="brush: jscript;">
$.mockjax({
  url: '/restful/api',
  response: function() {
    this.responseText = 'Hello world!';
  }
});
</pre>

<h2>Advanced Mocking Techniques</h2>

<p>At this point we&#8217;ve looked at a series of basic mocking techniques with Mockjax and will now unpack some of the additional functionality contained in the plugin.</p>

<h3>Simulating Response Time and Latency</h3>

<p>Simulating network and server latency for a mock is as simple as adding a <code>responseTime</code> property to your mock definition:</p>

<pre class="brush: jscript;">
$.mockjax({
  url: '/restful/api',
  // Simulate a network latency of 750ms
  responseTime: 750,
  responseText: 'A text response from the server'
});
</pre>

<h3>Simulating HTTP Response Statuses</h3>

<p>It&#8217;s also possible to simulate response statuses other than 200 (default for Mockjax) by simply adding a <code>status</code> property.</p>

<pre class="brush: jscript;">
$.mockjax({
  url: '/restful/api',
  // Server 500 error occurred
  status: 500,
  responseTime: 750,
  responseText: 'A text response from the server'
});
</pre>

<h3>Setting the Content-Type</h3>

<p>You can set the content type to associate with the mock response, in the example below, we&#8217;re setting a json content type.</p>

<pre class="brush: jscript;">
$.mockjax({
  url: '/restful/api',
  contentType: 'text/json',
  responseText: {
    hello: 'World!'
  }
});
</pre>

<h3>Setting Additional HTTP Response Headers</h3>

<p>Additional HTTP Response Headers may be provided by setting a key in the headers object literal:</p>

<pre class="brush: jscript;">
$.mockjax({
  url: '/restful/api',
  contentType: 'text/json',
  responseText: {
    hello: 'World!'
  },
  headers: {
    etag: 'xyz123'
  }
});
</pre>

<h3>Force Simulation of Server Timeouts</h3>

<p>Because of the way Mockjax was implemented, it takes advantage of jQuery&#8217;s internal timeout handling for requests. But if you&#8217;d like to force a timeout for a request you can do so by setting the <code>isTimeout</code> property to true:</p>

<pre class="brush: jscript;">
$.mockjax({
  url: '/restful/api',
  isTimeout: true
});
</pre>

<h3>Dynamically Generating Mock Definitions</h3>

<p>In some situations, all of your REST calls are based upon a URL schema. Mockjax has the ability for you to specify a callback function that is handed the <code>$.ajax</code> request settings. The callback function may then either return false to allow the request to be handled natively, or return an object literal with relevant Mockjax parameters set. Below is an example that rewrites all Ajax requests to proxy to static mocks:</p>

<pre class="brush: jscript;">
$.mockjax(function(settings) {
  // settings.url == '/restful/&lt;service&gt;'
  var service = settings.url.match(/\/restful\/(.*)$/);
  if ( service ) {
    return {
      proxy: '/mocks/' + service[1] + '.json'
    };
  }
  return;
});
</pre>

<h3>Dynamically Generating Mock Responses</h3>

<p>It&#8217;s also possible to dynamically generate the response text upon each request by implementing a callback function on the <code>response</code> parameter:</p>

<pre class="brush: jscript;">
$.mockjax({
  url: '/restful/webservice',
  dataType: 'json',
  response: function(settings) {
    this.responseText = { say: 'random ' + Math.random() };
  }
});
</pre>

<h3>Globally Defining Mockjax Settings</h3>

<p>It&#8217;s also possible to define the global defaults for all Mockjax requests by overwriting the <code>$.mockjaxSettings</code> object. By default the settings are as follows:</p>

<pre class="brush: jscript;">
$.mockjaxSettings = {
  status:        200,
  responseTime:  500,
  isTimeout:     false,
  contentType:   'text/plain',
  response:      '', 
  responseText:  '',
  responseXML:   '',
  proxy:         '',
  lastModified:  null,
  etag:          ''
};
</pre>

<p>To overwrite a particular settings such as the default content-type, you would do the following:</p>

<pre class="brush: jscript;">
$.mockjaxSettings.contentType = 'text/json';
</pre>

<h3>Removing Mockjax Handlers</h3>

<p>Remove all mockjax handlers:</p>

<pre class="brush: jscript;">
$.mockjaxClear();
</pre>

<h3>Remove Single Mockjax Handler</h3>

<pre class="brush: jscript;">
var id = $.mockjax({
   ...
});
$.mockjaxClear(id);
</pre>

<h2>Conclusion</h2>

<p>So there you have it, Mockjax unpacked! There are a number of additional posts in the pipeline surrounding this topic and how to apply and integrate it with your project. So stay tuned! In the meantime, the <a href="http://github.com/appendto/jquery-mockjax">plugin code is readily available on github</a> and feel free to report any issues you find in <a href="http://github.com/appendto/jquery-mockjax/issues">the plugin's github issue tracker</a>. Enjoy!</p>
<img src="http://feeds.feedburner.com/~r/EnterpriseJquery/~4/A0wmPXjiXMs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://enterprisejquery.com/2010/07/mock-your-ajax-requests-with-mockjax-for-rapid-development/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		<feedburner:origLink>http://enterprisejquery.com/2010/07/mock-your-ajax-requests-with-mockjax-for-rapid-development/</feedburner:origLink></item>
		<item>
		<title>Configuring UI widgets and interactions with .live() and .delegate()</title>
		<link>http://feedproxy.google.com/~r/EnterpriseJquery/~3/c-tgDEmZpjs/</link>
		<comments>http://enterprisejquery.com/2010/07/configuring-ui-widgets-and-interactions-with-live/#comments</comments>
		<pubDate>Sat, 17 Jul 2010 16:57:52 +0000</pubDate>
		<dc:creator>Andrew Wirick</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[jQuery UI]]></category>

		<guid isPermaLink="false">http://ejq.dev.appendto.com/?p=49</guid>
		<description><![CDATA[Configuring jQuery UI widgets often means making sure certain methods are called on a given DOM element (wrapped in jQuery) before usage occurs. We see this configuration pattern everywhere in jQuery UI. Great everyday examples include configuring the datepicker widgets, as well as draggable and droppable interactions. A relatively common example is something like the [...]
]]></description>
			<content:encoded><![CDATA[<p>Configuring jQuery UI widgets often means making sure certain methods are called on a given DOM element (wrapped in jQuery) before usage occurs. We see this configuration pattern everywhere in jQuery UI. Great everyday examples include configuring the <code>datepicker</code> widgets, as well as <code>draggable</code> and <code>droppable</code> interactions. A relatively common example is something like the following:</p>

<pre class="brush: jscript;">
$(function(){
  $('input.date:text').datepicker();
  //...
});
</pre>

<p><span id="more-49"></span>
Just to review, the selector we are using could be translated into words as &#8216;Select all elements that have a class named date and are also inputs of type text&#8217;.</p>

<p>This is functional &#8211; except when we get into dynamic additions of elements. As we utilize Ajax to give a richer experience, we run the risk of including a input of type text with the date class on it. This often leads one to start trying to configure UI widgets in the success callback of an Ajax request:</p>

<pre class="brush: jscript;">
$(function(){
  $('input.date:text').datepicker();
  //...
});

$.get('somePartialServerPage.html', function(data){
  $('#ajaxContainer')
    .html(data)
      .find('input.date:text')
        .datepicker()
        .end()
      .find('.myDraggableClass')
        .draggable({
          // config draggable here
        });
  });
});
</pre>

<p>This could certainly be refactored to be a better solution. We could use named functions to make sure we are DRY,  or we could use <code>.ajaxSuccess()</code> to handle adding the behavior with a single global event handler. Yet still the solution is not elegant and could be prone to many wasteful lookups.</p>

<p>This looks like a job for <code>.live()</code>. Attaching behavior to dynamically added elements is the most direct use case for <code>.live()</code>. But with interactions/widgets, often the widgets must be set up before interaction with the element occurs. Live (just like <code>.bind()</code>) presents us with no ways to do this directly.</p>

<p>However, with a little creativity and a good understanding of UI events we can find interesting ways of using live to attach widgets and interactions dynamically to elements.</p>

<h2>Scenario 1: Draggable</h2>

<p>Draggable interactions are fairly straightforward and familiar to most. When the users presses the mouse down, the draggable behavior will begin until a point where the user release the element by using a mouse up. Thus we must have the draggable behavior configured before the mousedown occurs. Can we use any events on that element to accomplish this task?</p>

<p>In order to be in a position to mousedown, the mouse will first have to fire a few other events. In particular we know that mouseenter and mouseover must fire previous to any mousedown interaction. If we use that event to configure behavior, we can ensure any element is draggable &#8211; even those dynamically added!</p>

<pre class="brush: jscript;">
$('.myDraggableClass').live('mouseenter',function(){
  $(this).draggable({
    // configure draggable here
  });
});
</pre>

<p>Now we must consider that multiple mouse enter events could fire as the user&#8217;s mouse exits and re-enters the elements. It would be prudent of us to check to see if the draggable interaction is already configured on that element. Looking under the hood, jQuery draggable add metadata to the element using jQuery&#8217;s <code>.data()</code> method. We can use this to our advantage to check and see if the behavior is set up:</p>

<pre class="brush: jscript;">
$('.myDraggableClass').live('mouseenter',function() {
  var $this = $(this);
  if(!$this.is(':data(draggable)')) {
    $this.draggable({
      // configure draggable here
    });
  }
});
</pre>

<p>Not only does this solution ensure that we will have draggable behavior attached to all elements, but it also scales quite well. If we were to have hundreds of images that were in the dom and supposed to be draggable, sluggish behavior could present itself. Here we only configure draggable interactions on those elements that are realistic candidates for the behavior.</p>

<h2>Scenario 2: Datepicker</h2>

<p>Datepicker presents a different challenge. While <code>mouseenter</code> will work in some cases, input boxes can gain focus and the datepicker behavior should begin without any mouse interaction.  Fortunately we can account for this by adding the datepicker as through the focus in event.  On top of that, the datepicker will immediately fire for us.</p>

<pre class="brush: jscript;">
  $('input.date:text').live('focusin', function() {
    var $this = $(this);
    if(!$this.is(':data(datepicker)')) {
      //this will attach a datepicker control &amp;amp; datepicker will immediately fire
      $this.datepicker();
    }
  });
</pre>

<p>We now have datepicker functionality on any appropriate input text element whether it is added at the initial page load or dynamically. </p>

<h2>Improving performance with delegate</h2>

<p>One possible way to improve performance would be to scope the context of the &#8220;live listeners&#8221; with the use of <code>.delegate()</code>. With <code>.live()</code> events the way they are written above the event propagation will occur up to the document level before the handlers will be called.  With delegate (or scoping live) we can catch the event happening lower in the dom tree.  For example let us say that the draggable events will all be occurring on the page within a container element.  This is a great candidate to use delegate to achieve the same behavior as above but with better performance.  This can also be a great solution where different regions on the page have draggable elements, but in each region you want a different configuration of draggable:</p>

<pre class="brush: jscript;">
$('#myContainer').delegate('.myDraggableClass', 'mouseenter', function() {
  var $this = $(this);
  if(!$this.is(':data(draggable)')) {
    $this.draggable({
      // configure draggable here
    });
  }
});
</pre>
<img src="http://feeds.feedburner.com/~r/EnterpriseJquery/~4/c-tgDEmZpjs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://enterprisejquery.com/2010/07/configuring-ui-widgets-and-interactions-with-live/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		<feedburner:origLink>http://enterprisejquery.com/2010/07/configuring-ui-widgets-and-interactions-with-live/</feedburner:origLink></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 8/13 queries in 0.003 seconds using apc
Content Delivery Network via ejq.a2cdn.net

Served from: enterprisejquery.com @ 2012-04-20 10:09:39 -->

