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

<channel>
	<title>onenaught.com &#187; JavaScript</title>
	<atom:link href="http://www.onenaught.com/posts/category/javascript/feed" rel="self" type="application/rss+xml" />
	<link>http://www.onenaught.com</link>
	<description>A blog on web standards, accessibility, css, javascript, xslt, and more</description>
	<lastBuildDate>Thu, 07 Oct 2010 09:26:45 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
<image>
		<title>One Naught</title>
		<url>http://www.onenaught.com/wp-content/themes/onenaught/images/onenaught.png</url>
		<link>http://www.onenaught.com</link>
		<width>116</width>
		<height>130</height>
		<description>OneNaught.com</description>
	</image>		<item>
		<title>Jonathan Snook&#8217;s jQuery Background Animation as a Plugin</title>
		<link>http://www.onenaught.com/posts/171/jonathan-snooks-jquery-background-animation-as-a-plugin</link>
		<comments>http://www.onenaught.com/posts/171/jonathan-snooks-jquery-background-animation-as-a-plugin#comments</comments>
		<pubDate>Wed, 01 Oct 2008 06:53:34 +0000</pubDate>
		<dc:creator>Anup Shah</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jquery plugins]]></category>

		<guid isPermaLink="false">http://www.onenaught.com/?p=171</guid>
		<description><![CDATA[<img class="post-img" align="left" src="/wp-content/uploads/animated-bg.png" alt="" /> Jonathan Snook recently posted a really neat <a href="http://snook.ca/archives/javascript/jquery-bg-image-animations/">background animation technique using jQuery</a>. This was something I was looking for and it seemed like a good candidate for a jQuery plugin.

So, following on from my recent post about <a href="http://www.onenaught.com/posts/85/turn-your-jquery-code-into-a-richer-unit-testable-plugin">turning jQuery code into richer, unit testable plugin code</a>, I thought I'd describe the quick process of doing so here. (It's worth reading Snook's post first though!)]]></description>
			<content:encoded><![CDATA[<p><img class="post-img" src="http://www.onenaught.com/wp-content/uploads/animated-bg.png" alt="" /> Jonathan Snook recently posted a really neat <a href="http://snook.ca/archives/javascript/jquery-bg-image-animations/">background animation technique using jQuery</a>. This was something I was looking for and it seemed like a good candidate for a jQuery plugin.</p>
<p>So, following on from my recent post about <a href="http://www.onenaught.com/posts/85/turn-your-jquery-code-into-a-richer-unit-testable-plugin">turning jQuery code into richer, unit testable plugin code</a>, I thought I&#8217;d describe the quick process of doing so here. (It&#8217;s worth reading Snook&#8217;s post first though!)</p>
<p>The general steps discussed to achieve this are as follows:</p>
<ol>
<li>Add additional keyboard accessibility</li>
<li>A first attempt plugin</li>
<li>A plugin that might be unit testable</li>
</ol>
<h3 id="toc-add-additional-keyboard-accessibility">Add additional keyboard accessibility</h3>
<p>I posted a comment on Snook&#8217;s post to say additional hover and blur events should do the trick, so here is an example applied to one of the four demo menus he had with those events added:</p>
<pre class="syntax-highlight:js">
$(&#039;#d a&#039;)
    .css( {backgroundPosition: &quot;0 0&quot;} )
    .mouseover(function(){
        $(this).stop().animate({backgroundPosition:&quot;(0 -250px)&quot;}, {duration:500})
    })
    .mouseout(function(){
        $(this).stop().animate({backgroundPosition:&quot;(0 0)&quot;}, {duration:500})
    })
// I added these event handlers:
    .focus(function(){
        $(this).stop().animate({backgroundPosition:&quot;(0 -250px)&quot;}, {duration:500})
    })
    .blur(function(){
        $(this).stop().animate({backgroundPosition:&quot;(0 0)&quot;}, {duration:500})
    })
</pre>
<h3 id="toc-a-first-attempt-plugin">A first attempt plugin</h3>
<p>The above code as a plugin might look something like this:</p>
<pre class="syntax-highlight:js">
(function($) {
    $.fn.animatedBackground = function(options) {

    // build main options before element iteration by extending the default ones
    var opts = $.extend({}, $.fn.animatedBackground.defaults, options);

    function startAnimation() {
        $(this).stop().animate(
           {backgroundPosition:opts.backgroundPositionStart},
           {duration:opts.duration}
        );
    }

    function stopAnimation() {
        var animationConfig = { duration:opts.duration };
        if (opts.complete)
            animationConfig.complete = opts.complete;

        $(this).stop().animate(
            {backgroundPosition:opts.backgroundPositionEnd},
            animationConfig
        );
    }

    // for each side note, do the magic.
    return $(this)
        .css( {backgroundPosition: opts.backgroundPositionInit} )
        .mouseover(startAnimation)
        .mouseout(stopAnimation)
        .focus(startAnimation)
        .blur(stopAnimation)
    };

    // plugin defaults
    $.fn.animatedBackground.defaults = {
        backgroundPositionInit : &quot;0 0&quot;,
        backgroundPositionStart : &quot;(0 0)&quot;,
        backgroundPositionEnd : &quot;(0 0)&quot;,
        durationStart : 500,
        durationEnd : 500,
        complete : null
    };
})(jQuery);
</pre>
<p>The above is just a quick 2 minute thing &#8212; I am sure with more thought the plugin options could be made even more flexible. But this will do for the purpose of this post.</p>
<p>For each of the 4 demo menus Snook provided, you could then call them as follows:</p>
<pre class="syntax-highlight:js">
$(function(){
    $(&#039;#a a&#039;)
        .animatedBackground(
            {
                backgroundPositionInit : &quot;-20px 35px&quot;,
                backgroundPositionStart : &quot;(-20px 94px)&quot;,
                backgroundPositionEnd : &quot;(40px 35px)&quot;,
                durationEnd : 200,
                complete : function(){
                    $(this).css({backgroundPosition: &quot;-20px 35px&quot;});
                }
            }
        );

    $(&#039;#b a&#039;)
        .animatedBackground(
            {
                backgroundPositionStart : &quot;(-150px 0)&quot;,
                backgroundPositionEnd : &quot;(-300px 0)&quot;,
                durationEnd : 200,
                complete : function(){
                    $(this).css({backgroundPosition: &quot;0 0&quot;});
                }
            }
        );

    $(&#039;#c a, #d a&#039;)
        .animatedBackground(
            { backgroundPositionStart : &quot;(0 -250px)&quot; }
        );
});
</pre>
<p>(Examples c and d are combined with one selector, while a and b each have more complex options.)</p>
<p>In the &#8220;simple&#8221; cases (c and d) a very small amount of code is needed to use the plugin. For (a and b) if you were only going to use this once, it might be questionable whether the plugin for this is worth the effort!</p>
<h3 id="toc-unit-testable-plugin">Unit testable plugin?</h3>
<p>Some plugins might be so small that unit testing them may not seem beneficial or worth the effort. In this particular case, it is not clear if it is necessary. However, for the purpose of this post at least it may be a useful exercise. So, these might be some things to bear in mind:</p>
<ul>
<li>The bulk of the plugin relies on <code>animate()</code> which works asynchronously. Unit testing asynchronous calls can be tricky with QUnit. More importantly, we are not trying to unit test <code>animate()</code> but our plugin code instead.</li>
<li>The function handler for each mouse/focus/blur event could be made into a default plugin function</li>
<li>Unit tests can then replace the default function with a mock function to confirm that the rest of the plugin works with the various configuration options passed in.</li>
</ul>
<p>To achieve the above, a simple step might just be to make the private <code>startAnimation()</code> and <code>stopAnimation()</code> methods public.</p>
<p>This can be done a few ways, e.g. keep those private methods and make them call the public ones, or wherever the private ones are called, make them call the public ones, etc.</p>
<p>The two public methods would look something like this:</p>
<pre class="syntax-highlight:js">
$.fn.animatedBackground.startAnimation = function($el, opts) {
    $el.stop().animate(
        {backgroundPosition:opts.backgroundPositionEnd},
        {duration:opts.duration}
    );
}

$.fn.animatedBackground.stopAnimation = function($el, opts) {
    var animationConfig = { duration:opts.duration };
    if (opts.complete)
        animationConfig.complete = opts.complete;

    $el.stop().animate(
        {backgroundPosition:opts.backgroundPositionEnd},
        animationConfig
    );
}
</pre>
<p><a class="try-it" href="/examples/jquery/animatedBackground/jquery.animatedBackground.test.html">Here&#8217;s a page with a unit testable version of the plugin which also has the original menu examples</a></p>
<h3 id="toc-was-it-worth-adding-extra-code-to-make-it-unit-testable">Was it worth adding extra code to make it unit testable?</h3>
<p>The testable plugin version is a bit larger than the original (ignoring minification and gzipping benefits to remove a lot of the difference).</p>
<p>Was it therefore worth changing in this way from the original?</p>
<p>In my opinion, the initial plugin version would probably suffice, especially if likely to be used across a few small projects.</p>
<p>If, on the other hand, you were going to use it in a more critical scenario, then unit testing what you can could be useful.</p>
<p>A principle of test driven development is to write unit tests first. In this case as it was existing code, it seemed okay to do it in the order described above. Furthermore, sometimes it feels tricky to always stick to that principle religiously, and writing unit tests afterwords might be okay if the plugin is smallish, perhaps?</p>
<h3 id="toc-summary">Summary</h3>
<p>So, many thanks for Jonathan Snook for his post. That technique is useful for me in some other projects.</p>
<p>This post hopefully shows that even small snippets of code can be turned into a plugin, sometimes unit testable ones. Whether that is worth your efforts depends on your need and audience.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.onenaught.com/posts/171/jonathan-snooks-jquery-background-animation-as-a-plugin/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Turn your jQuery code into a richer, unit testable, plugin</title>
		<link>http://www.onenaught.com/posts/85/turn-your-jquery-code-into-a-richer-unit-testable-plugin</link>
		<comments>http://www.onenaught.com/posts/85/turn-your-jquery-code-into-a-richer-unit-testable-plugin#comments</comments>
		<pubDate>Sun, 28 Sep 2008 20:07:53 +0000</pubDate>
		<dc:creator>Anup Shah</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jquery plugins]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://www.onenaught.com/?p=85</guid>
		<description><![CDATA[<img class="post-img" align="left" src="/wp-content/uploads/qunit.png" alt="" /> I find myself increasingly using <a href="http://jquery.com">jQuery</a> as my JavaScript framework of choice.

It's by-line of "write less, do more" really seems apt.

But sometimes, by writing just that little bit extra, you can do even more.

For example, I often try to do the following:
<ul>
	<li>Make most jQuery code into reusable plugins</li>
	<li>Use the jQuery plugin development pattern for added flexibility</li>
	<li>Use QUnit to unit test JavaScript</li>
	<li>Combine the two approaches to drive out a richer API for the plugin</li>
</ul>

By unit testing with QUnit, I find I often need to trigger additional events or add additional code from within the plugin so the test can be meaningful.

But this extra code isn't only useful for testing, it becomes a useful part of the plugin's API, improving its functionality and flexibility without sacrificing maintainability and readability of the code.

I'll try to demonstrate that in this post.]]></description>
			<content:encoded><![CDATA[<p><img class="post-img" src="http://www.onenaught.com/wp-content/uploads/qunit.png" alt="" /> I find myself increasingly using <a href="http://jquery.com">jQuery</a> as my JavaScript framework of choice.</p>
<p>It&#8217;s by-line of &#8220;write less, do more&#8221; really seems apt.</p>
<p>But sometimes, by writing just that little bit extra, you can do even more.</p>
<p>For example, I often try to do the following:</p>
<ul>
<li>Make most jQuery code into reusable plugins</li>
<li>Use the jQuery plugin development pattern for added flexibility</li>
<li>Use QUnit to unit test JavaScript</li>
<li>Combine the two approaches to drive out a richer API for the plugin</li>
</ul>
<p>By unit testing with QUnit, I find I often need to trigger additional events or add additional code from within the plugin so the test can be meaningful.</p>
<p>But this extra code isn&#8217;t only useful for testing, it becomes a useful part of the plugin&#8217;s API, improving its functionality and flexibility without sacrificing maintainability and readability of the code.</p>
<p>I&#8217;ll try to demonstrate that in this post.</p>
<h3 id="toc-make-most-of-your-jquery-code-into-reusable-plugins">Make most of your jQuery code into reusable plugins</h3>
<p>In many cases, where there is a block of jQuery code initializing something, it is a candidate for a plugin.</p>
<p>It took me a little while before I gave jquery plugins a go, thinking it will be complex and I won&#8217;t have time. But, it turns out to be really simple, elegant and useful for both simple and complicated scenarios.</p>
<h4 id="toc-example-to-create-a-dynamic-side-note-toggler">Example to create a dynamic side note toggler</h4>
<p>Lets take a simple example for illustration: suppose I have some HTML that acts as an aside, or side note, and that I want to toggle its appearance.</p>
<p>Lets say we agree this kind of HTML format for it (or microformat):</p>
<pre class="syntax-highlight:html">
&lt;p&gt;Some text before the side note.&lt;/p&gt;

&lt;div class=&quot;side-note&quot;&gt;
	&lt;p&gt;Any HTML could go here including&lt;/p&gt;
	&lt;ul&gt;
		&lt;li&gt;Bulleted lists&lt;/li&gt;
		&lt;li&gt;Tabular data&lt;/li&gt;
		&lt;li&gt;Images&lt;/li&gt;
	&lt;/ul&gt;

	&lt;div class=&quot;side-note&quot;&gt;
		&lt;p&gt;Even nested side notes, if that is of any use!&lt;/p&gt;
	&lt;/div&gt;
&lt;/div&gt;

&lt;p&gt;Some text after the side note.&lt;/p&gt;
</pre>
<p>The first way I&#8217;d do it might be something like this:</p>
<pre class="syntax-highlight:js">
$(document).ready(function() {
    $('.side-note').each(function() {
        $(this)
            .addClass('dynamic-side-note')
            .hide()
            .wrap('&lt;div class=&quot;dynamic-side-note-container&quot;&gt;&lt;/div&gt;')
            .before('&lt;h3 class=&quot;toggler&quot;&gt;&lt;a href=&quot;#&quot;&gt;Side note:&lt;/a&gt;&lt;/h3&gt;')
            .parent(0).find('&gt; h3.toggler &gt; a').click(function() {
                $(this).parents('.dynamic-side-note-container').eq(0).find('&gt; .dynamic-side-note').slideToggle();
                return false;
            });
    });
});
</pre>
<p>I could have added a click event handler to the <code>h3</code> header above, but using an anchor adds keyboard accessibility.</p>
<p>(The CSS selector could also be improved, e.g. to narrow it down to only side-notes in some content div, e.g. <code>$('#content .side-note')</code>.)</p>
<p><a class="try-it" href="/examples/jquery/side-notes/no-plugin/">Here is a working example</a></p>
<h4 id="toc-as-a-simple-jquery-plugin">As a simple jQuery plugin</h4>
<p>The above works. But, we can move most of the above code into a jQuery plugin.</p>
<p>Why bother? We can gain a bit more flexibility, such as the ability to use any selector, not rely on a <code>side-note</code> class. We could pass in other parameters such as what the text for the side note toggler/header should be, etc.</p>
<p>As a first attempt, the plugin might look something like this:</p>
<pre class="syntax-highlight:js">
$.fn.sideNotes = function() {
    // returning this way allows chaining
    return $(this)
        .addClass('dynamic-side-note')
        .hide()
        .wrap('&lt;div class=&quot;dynamic-side-note-container&quot;&gt;&lt;/div&gt;')
        .before('&lt;h3 class=&quot;toggler&quot;&gt;&lt;a href=&quot;#&quot;&gt;Side note:&lt;/a&gt;&lt;/h3&gt;')
        .parent(0).find('&gt; h3.toggler &gt; a').click(function() {
            $(this).parents('.dynamic-side-note-container').eq(0).find('&gt; .dynamic-side-note').slideToggle();
            return false;
        });
};
</pre>
<p>We then just need to invoke the plugin:</p>
<pre class="syntax-highlight:js">
jQuery(function() {
    $(&#039;.side-note&#039;).sideNotes();
});
</pre>
<p>(Note how you could use any selector now not just <code>.side-note</code> as above.)</p>
<p><a class="try-it" href="/examples/jquery/side-notes/plugin-1-simple/">Here is a working example using the simple plugin</a></p>
<p>Plugins also make it easier to pass in more options for configuration. The next example uses a useful pattern for plugin development that also shows a nice way to handle plugin options:</p>
<h3 id="toc-use-the-jquery-plugin-development-pattern-for-added-flexibility">Use the jQuery plugin development pattern for added flexibility</h3>
<p>The post, <a href="http://www.learningjquery.com/2007/10/a-plugin-development-pattern">A Plugin Development Pattern (for jQuery)</a>, from the <a href="http://www.learningjquery.com">Learning jQuery</a> blog is really useful.</p>
<p>It provides a good way to write plugins that also get the following features:</p>
<ul>
<li>Configurability by passing in options</li>
<li>Default options to keep invoking code small and neat</li>
<li>A closure where you split your code out into manageable private functions, etc., if you need</li>
<li>Ensuring that your plugin support chaining</li>
<li>And more</li>
</ul>
<p>Using some of those ideas, here is what we might come up with for the sideNotes plugin:</p>
<pre class="syntax-highlight:js">
(function($) {
    $.fn.sideNotes = function(options) {

    // build main options before element iteration by extending the default ones
    var opts = $.extend({}, $.fn.sideNotes.defaults, options);

    // for each side note, do the magic.
    return $(this)
        .hide()
        .wrap('&lt;div class="dynamic-side-note"&gt;&lt;/div&gt;')
        .before('&lt;h3 class=&quot;toggler&quot;&gt;&lt;a href="#"&gt;' + opts.sideNoteToggleText +'&lt;/a&gt;&lt;/h3&gt;')
        .parent(0).find('&gt; h3.toggler &gt; a').click(function() {
            $(this).parents('.dynamic-side-note').eq(0).find('&gt; .side-note').slideToggle();
            return false;
        });
    };

    // plugin defaults
    $.fn.sideNotes.defaults = {
        sideNoteToggleText : 'Side note:'
    };
})(jQuery);
</pre>
<p>And invoking the plugin is the same as before:</p>
<pre class="syntax-highlight:js">
jQuery(function() {
    $('.side-note').sideNotes();

    // or overriding the default side note toggle text:
    // $('.side-note').sideNotes({ sideNoteToggleText : 'As an aside:' });
});
</pre>
<p><a class="try-it" href="/examples/jquery/side-notes/plugin-2-pattern/">Here is a working example using the plugin pattern</a></p>
<h3 id="toc-unit-testing-the-jquery-plugin">Unit testing the jQuery plugin</h3>
<p>As the plugin code is reasonably well encapsulated, we can create some unit tests for this plugin. </p>
<p>Unit testing jQuery (as with any code) gives you confidence in maintaining it. For example, when refactoring code, unit tests give you confidence that you can do it without breaking things. Plugins, almost by definition are good candidates for unit testing.</p>
<h4 id="toc-examples-of-unit-tests-for-this-plugin">Examples of unit tests for this plugin</h4>
<p>Our example side note plugin is quite simple, so the unit tests will likely be small in number. Types of tests we might include are the following:</p>
<ul>
<li>Test that we can expand/collapse a side note</li>
<li>Test that we can expand/collapse a side note many times and ensure the toggle state reported is correct each time</li>
<li>Test that when the side note plugin has run, all the side notes are collapsed initially</li>
<li>Test that we can change the toggle text to something else</li>
</ul>
<p>And so on.</p>
<p>Remember, the unit tests should not test the <code>slideToggle()</code> method we happened to use (as that should be unit tested itself, and we may use other ways of toggling the side note in the future). Instead, we just need to unit test our code and plugin functionality.</p>
<p>So ideally, we might even want to &#8220;mock&#8221; the <code>slideToggle()</code>, if necessary.</p>
<h4 id="toc-use-qunit-to-unit-test-javascript">Use QUnit to unit test JavaScript</h4>
<p><a href="http://docs.jquery.com/QUnit">QUnit</a> is a unit testing framework, used internally by jQuery itself for all its core JavaScript, and now opened up and documented for others to use, too. It is a simple framework to support the creation and execution of tests.</p>
<p>The tests are run in a browser. You could automate it against all your target browsers by using something like <a href="http://selenium.openqa.org/">Selenium</a>.</p>
<p>The framework is in its early days (a setup and teardown set of methods would be nice, for example), but is rich enough to get started with it.</p>
<p><a class="try-it" href="/examples/jquery/side-notes/plugin-3-unit-tested/jquery.sideNotes.test.html">Here is a QUnit test page for the side note plugin</a></p>
<p>(I included a manual test area as this can sometimes be useful where visual confirmation is useful or automated tests of some parts is not possible/easy. Having this all in one place can be handy.)</p>
<h3 id="toc-using-unit-tests-and-plugins-helps-create-a-richer-api-for-the-plugin">Using unit tests and plugins helps create a richer API for the plugin</h3>
<p>To write testable code, you may find you need to provide more hooks in the code. Yet, you probably don&#8217;t want to pollute your code so much that it is detrimental to performance or maintainability.</p>
<h4 id="toc-triggering-events-on-the-plugin-for-added-flexibility">Triggering events on the plugin for added flexibility</h4>
<p>In the unit test example page, how did we manage to get unit tests to confirm a side note had been toggled when we didn&#8217;t have any callback for it?</p>
<p>The first idea people might have is to pass a callback that a plugin user can point to in the options when invoking the plugin, something like this:</p>
<pre class="syntax-highlight:js">
jQuery(function() {
    $('.side-note').sideNotes(
        {
            toggled : function() { console.log('side note was toggled'); }
        }
    );
});
</pre>
<p>That looks useful; the unit test can provide a callback when it invokes the plugin.</p>
<p>However, that limits us to just one observer, the one that invoked the side note plugin in the first place.</p>
<p>But we can go one step further: trigger events. This allows more than one observer to watch for the event. This is achieved using jQuery&#8217;s <code>trigger()</code> and <code>bind()</code> methods.</p>
<p>By having unit tests watching for these events, it does not distort the plugin code; it enhances its API making the event useful for a real plugin user, if they need it.</p>
<p>In our side note plugin example, when we call <code>slideToggle()</code> we can trigger an event when the toggling has completed:</p>
<pre class="syntax-highlight:js">
// all the stuff that gets to the
// slide toggle bit comes here!
.slideToggle( function() {
    $(this).trigger('sideNoteToggled');
});
</pre>
<p>If your code cares when this happens, you can bind to this event, something like this:</p>
<pre class="syntax-highlight:js">
$('.side-note').bind('sideNoteToggled', eventHandlerGoesHere);
</pre>
<p>(A fuller example below uses <code>trigger()</code> to also pass the expanded/collapsed state in conjunction with some ARIA information.)</p>
<h4 id="toc-providing-default-implementations-that-can-be-replaced-or-mocked-for-unit-testing">Providing default implementations that can be replaced (or mocked for unit testing)</h4>
<p>One particular challenge I had with unit testing this side note example was that the <code>slideToggle()</code> method used by the plugin, internally runs asynchronously (using setTimeout etc).</p>
<p>Writing normal unit test code means the test can finish before the animation has run.</p>
<p>Even though I tried to use <code>setTimeout()</code> on the tests themselves to try and make them wait for the sideNote to finish toggling, and passing in the fastest speed possible to the slideToggle method, it wasn&#8217;t always right, and not consistent across all browsers.</p>
<p>This gave me the opportunity to do a few things:</p>
<ul>
<li>Encapsulate the call to slideToggle in another method</li>
<li>Make that method the default implementation, but overrideable</li>
<li>Use this to provide a mock slide toggler for testing purposes</li>
</ul>
<p>With jQuery&#8217;s plugin architecture providing a default implementation is quite straight forward:</p>
<pre class="syntax-highlight:js">
$.fn.sideNotes.toggle = function() {
    $(this).slideToggle(function() {
        $(this).trigger('sideNoteToggled');
    });
};
</pre>
<p>Mocking the <code>slideToggle()</code> call is nice because we don&#8217;t want to test external code in our unit tests; that should have been unit tested by whoever wrote that (the jQuery team I imagine! I&#8217;ll have to look at their unit tests when I get a moment to see how they overcome asynchronous issue &#8212; there is some mechanism to provide <code>stop()</code> and <code>start()</code> methods for AJAX testing and I tried this here, but still wasn&#8217;t getting consistent results).</p>
<p>In our example, we can overwrite the the default toggle method to simply use <code>toggle()</code> instead of <code>slideToggle()</code>, which is a non-animated version that runs and completes immediately.</p>
<p>This makes writing the testing code a bit simpler too. (There are one or two bits that I did that didn&#8217;t feel too great in my opinion, such as the way I chose to expose the post toggle action, but that is perhaps for another day to sort out!)</p>
<p>To override the default implementation, you can redefine <code>sideNotes.toggle</code> in your code, something like this:</p>
<pre class="syntax-highlight:js">
$.fn.sideNotes.toggle = function() {
    $(this).toggle().trigger('sideNoteToggled');
};
</pre>
<h4 id="toc-example-qunit-test-code">Example QUnit test code</h4>
<p>So taking the above considerations this is what we might have in our QUnit unit test code:</p>
<p>This code block shows a test util object to help instrument the test, and then at the bottom, an example of a mock object to replace the <code>slideToggle()</code> call.</p>
<pre class="syntax-highlight:js">
(function(){
    var testUtils = {
        isExpandedCount : 0,
        isCollapsedCount : 0,

        defaultTestOptions : {
            selector : &#039;#example .side-note&#039;,
            sideNoteOptions : {},
            speed : &#039;fast&#039;
        },

        // a crude setup like method, which QUnit currently doesn&#039;t have
        init : function(options) {
            testUtils.reset();

            var opts = $.extend({ sideNoteOptions : {} }, testUtils.defaultTestOptions, options);

            // tests assume the relevant HTML is present on the page the test is running
            $(opts.selector)
                .bind(&#039;sideNoteToggled&#039;, testUtils.sideNoteToggled)
                    .sideNotes(opts.sideNoteOptions);

            return $(opts.selector);
        },

        sideNoteToggled : function(event, isExpanded) {
            isExpanded ? testUtils.isExpandedCount++ : testUtils.isCollapsedCount++;

            $(event.target).trigger(&#039;sideNoteToggleCaptured&#039;);
        },

        // until there is an explicit tear down method this will have to do
        reset : function() {
            $(&#039;#example .side-note&#039;).unbind(&#039;sideNoteToggled&#039;);
            testUtils.isExpandedCount = 0;
            testUtils.isCollapsedCount = 0;
        }
    };

    // mock the slideToggle. We are not testing that.
    function mockSideNoteToggle() {
        $(this).toggle();

        $.fn.sideNotes.toggled.call(this);
    }

    // keep the original implementation if we want to use it later
    $.fn.sideNotes.originalToggler = $.fn.sideNotes.toggle;

    // override the default toggle method with the mock
    $.fn.sideNotes.toggle = mockSideNoteToggle;
})();
</pre>
<p>We can then write unit tests, such as this one (note this code would go inside the anonymous function used above):</p>
<pre class="syntax-highlight:js">
module(&quot;Single toggle tests&quot;);

test(&quot;Test side note is expanded when toggled&quot;, function() {
    var $sideNote = testUtils.init();

    $sideNote.each(function() {
        equals($(this).attr(&#039;aria-expanded&#039;), &#039;false&#039;, &quot;Side not starts as collapsed&quot;);
    });

    $(&#039;#example&#039;)
        .find(&#039;.side-note:eq(0)&#039;).bind(&#039;sideNoteToggleCaptured&#039;, function() {
            equals(testUtils.isExpandedCount, 1, &quot;A node has been expanded&quot;);
            equals(testUtils.isCollapsedCount, 0, &quot;No nodes have been collapsed after initialization&quot;);
            equals(this[&#039;aria-expanded&#039;], true, &quot;Node’s aria state is expanded&quot;);
        })
        .end()
            .find(&#039;.toggler &gt; a:eq(0)&#039;).click();
            // calling click() is like simulating the user action to start the test
});
</pre>
<p>In the above example, the following is happening:</p>
<ol>
<li>The call to init() creates/initializes the sideNote plugin</li>
<li>We then assert that the ARIA state reports each side note is not expanded</li>
<li>We then find each side note and bind to the sideNoteToggleCaptured event (which is raised by the unit test utility shown earlier, not by the plugin itself)</li>
<li>We then simulate a user action by finding the toggler and clicking it</li>
<li>The simulated click() makes the plugin eventually trigger the <code>sideNoteToggled</code> event, which the testUtils object will catch.</li>
<li>The test util will catch that event and update the various testing counters and itself trigger the <code>sideNoteToggleCaptured</code> event.</li>
<li>Finally at this point, we can run our assertions, such as confirming the expected number of times the side note was expanded/collapsed and what the expected ARIA state should be (in this example seen by the use of the <code>equals()</code> function).</li>
</ol>
<p><a class="try-it" href="/examples/jquery/side-notes/plugin-3-unit-tested/jquery.sideNotes.test.html">See the full example for more unit tests</a></p>
<p>The additional tests in the full example also show the side note being dynamically created per test run, so you don&#8217;t always have to have the HTML set up exactly as needed for every test, manually.</p>
<p>The unit test code in that example can probably be further improved by refactoring those test() functions into a helper function where you pass in callbacks to run when the test has completed, how many clicks you want to invoke, etc, but that is for another time!</p>
<h4 id="toc-final-plugin-code">Final plugin code</h4>
<p>Here is the final plugin code (with some additional options not discussed above):</p>
<pre class="syntax-highlight:js">
(function($) {
    $.fn.sideNotes = function(options) {

        // build main options before element iteration
        var opts = $.extend({}, $.fn.sideNotes.defaults, options);

        // iterate and process each matched element
        return $(this)
            .addClass('dynamic-side-note').hide()
            .attr('aria-expanded', false)
            .wrap('&lt;div class=&quot;dynamic-side-note-container&quot;&gt;&lt;/div&gt;')
            .before('&lt;' + opts.toggleElement + '&gt;&lt;a class=&quot;toggler&quot; href=&quot;#&quot;&gt;' + opts.sideNoteToggleText +'&lt;/a&gt;&lt;/' + opts.toggleElement + '&gt;')
            .parent(0)
                .find(opts.toggleElement + '.toggler &gt; a')
                    .click(doToggle);

        // example of private method
        function doToggle() {
            $(this)
                .parents('.dynamic-side-note-container').eq(0)
                    .find('&gt; .dynamic-side-note').each( function() {
                        $.fn.sideNotes.toggle.call(this, options);
                    });

            return false;
        }
    };

    // plugin defaults
    $.fn.sideNotes.defaults = {
        sideNoteToggleText : 'Side note:',
        speed : 'normal',
        toggleElement : 'h3'
    };

    // default implementation for the toggler (public. i.e. overrideable)
    $.fn.sideNotes.toggle = function(options) {
        $(this).slideToggle(options.speed, $.fn.sideNotes.toggled);
    };

    // default callback when toggle completed (public. i.e. overrideable)
    $.fn.sideNotes.toggled = function() {
        this['aria-expanded'] = this['aria-expanded'] === true ? false : true;

        $(this).trigger('sideNoteToggled', this['aria-expanded']);
    };
})(jQuery);
</pre>
<h4 id="toc-is-the-additional-lines-of-code-for-a-plugin-worth-it">Is the additional lines of code for a plugin worth it?</h4>
<p>The plugin used in the unit tested example is larger in terms of lines of code than the very first attempt, above.</p>
<p>In this case, the lines of code is still quite small, and as plugins get even larger the percentage difference is likely to be small (the size difference is more noticeable in smaller code samples, such as this contrived side note example).</p>
<p>Minimizing and gzipping JavaScript, plus using <a href="http://www.onenaught.com/posts/17/web-site-performance-expires-header">far future expires header for better caching</a> would further reduce the percentage difference in file sizes of the two approaches.</p>
<p>Depending on your needs, this may be a reasonable trade-off in return for additional flexibility.</p>
<h3 id="toc-summary">Summary</h3>
<p>So, in many cases, jQuery code can be made reusable by making it into a plugin. Any time you find yourself writing a block of code, say inside a $(document).ready() block, consider converting it into a plugin and calling it.</p>
<p>When making the plugin, consider the following:</p>
<ul>
<li>Provide various options for flexibility</li>
<li>Write unit tests to test your plugin</li>
<li>Trigger important events inside your plugin to aide unit testability, and in doing so, increase flexibility of your plugin even more.</li>
</ul>
<p>When you get the hang of this, it is probably better to write the unit tests before the actual plugin code. This will help focus on what is needed and what the plugin needs to expose in terms of capability. To be honest, at times I have found it easier to retrofit a plugin with unit tests. I probably need to be a bit more disciplined to write tests first!</p>
<p>(While there are a number of enhancements that could be added to this, the main thing I&#8217;d probably do is rename the plugin to something more generic than just a side note toggler, but I will leave that for the reader to do, and remember to refactor the unit tests accordingly!)</p>
<p>Hope that is useful?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.onenaught.com/posts/85/turn-your-jquery-code-into-a-richer-unit-testable-plugin/feed</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>Google to host a number of JavaScript libraries</title>
		<link>http://www.onenaught.com/posts/80/google-to-host-a-number-of-javascript-libraries</link>
		<comments>http://www.onenaught.com/posts/80/google-to-host-a-number-of-javascript-libraries#comments</comments>
		<pubDate>Wed, 28 May 2008 13:01:32 +0000</pubDate>
		<dc:creator>Anup Shah</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://www.onenaught.com/?p=80</guid>
		<description><![CDATA[<img src="http://www.onenaught.com/wp-content/uploads/js-libraries.png" alt="" class="post-img" align="left" /> <a href="http://ajaxian.com/archives/announcing-ajax-libraries-api-speed-up-your-ajax-apps-with-googles-infrastructure">Google just announced their AJAX Library API</a>, where Google will host many major JavaScript frameworks for you, such as jQuery, Prototype, Mootools, Dojo, etc.

This will allow you to write web pages that refer to those scripts rather than copies on your own site, reducing your bandwidth, but also leveraging the infrastructure capabilities of Google, such as their content distributed network (which means users would be served those files from a location much closer to them), properly compressed, minified, cacheable files, etc.]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.onenaught.com/wp-content/uploads/js-libraries.png" alt="" class="post-img" /> <a href="http://ajaxian.com/archives/announcing-ajax-libraries-api-speed-up-your-ajax-apps-with-googles-infrastructure">Google just announced their AJAX Library API</a>, where Google will host many major JavaScript frameworks for you, such as jQuery, Prototype, Mootools, Dojo, etc.</p>
<p>This will allow you to write web pages that refer to those scripts rather than copies on your own site, reducing your bandwidth, but also leveraging the infrastructure capabilities of Google, such as their content distributed network (which means users would be served those files from a location much closer to them), properly compressed, minified, cacheable files, etc.</p>
<p>In addition, if your visitors have been to other sites using the same technique, they would not need to download the same libraries all over again, and with increasingly rich web sites, these files can get quite large.</p>
<p>So, if you use jQuery, you can use this in your web pages:</p>
<pre><code>&lt;script type=&quot;text/javascript&quot; src=&quot;http://<strong>ajax.googleapis.com</strong>/ajax/libs/jquery/1.2.6/jquery.min.js&quot;&gt;&lt;/script&gt;</code></pre>
<p>Of course, this is not for everyone, and it may be worth bearing in mind some <a href="http://peter.michaux.ca/article/7906">concerns</a> raised by Peter Michaux, who also provides a useful way to handle the scenario where you think access to Google from the user&#8217;s location might be restricted (e.g. blocked from a paranoid office!):</p>
<pre><code>&lt;script type=&quot;text/javascript&quot; src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
  if (!jQuery) {
    // load from your own server
    document.write('&lt;script type=&quot;text/javascript&quot; src=&quot;/js/jquery.min.js&quot;&gt;&lt;\/script&gt;');
  }
&lt;/script&gt;
</code></pre>
<p>Still, it could be a useful technique to further improve the download/load performance for a number of sites.</p>
<p>A number of months back, Yahoo was the first to announce something like this when they said they would <a href="http://yuiblog.com/blog/2007/02/22/free-yui-hosting">host their YUI library for you</a> so it is good to see others getting into this.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.onenaught.com/posts/80/google-to-host-a-number-of-javascript-libraries/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Day 2: @media ajax November 2007</title>
		<link>http://www.onenaught.com/posts/37/day-2-media-ajax-november-2007</link>
		<comments>http://www.onenaught.com/posts/37/day-2-media-ajax-november-2007#comments</comments>
		<pubDate>Thu, 22 Nov 2007 22:28:51 +0000</pubDate>
		<dc:creator>Anup Shah</dc:creator>
				<category><![CDATA[General Web Development]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[@media ajax]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[JavaScript2]]></category>

		<guid isPermaLink="false">http://www.onenaught.com/posts/37/day-2-media-ajax-november-2007</guid>
		<description><![CDATA[<p><img src="/wp-content/uploads/at-media-ajax.gif" alt="@media ajax 2007" class="post-img" align="left" /> My impression of day 2 at @media ajax, the ajax/javascript conference with some of the leading figures in this area.</p>]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.onenaught.com/wp-content/uploads/at-media-ajax.gif" alt="@media ajax 2007" class="post-img" /> A previous post summarized <a href="http://www.onenaught.com/posts/36/day1-media-ajax-november-2007">day 1 of @media ajax</a> which looked at general issues of JavaScript on the web.</p>
<p>This post is a summary of day 2, a more technical look at JavaScript and its future.</p>
<p><span id="more-37"></span></p>
<h3 id="toc-javascript-2-and-the-open-web">JavaScript 2 and The Open Web</h3>
<p>By <a href="http://weblogs.mozillazine.org/roadmap/">Brendan Eich</a>, the inventor of JavaScript.</p>
<p>Good talk on some details about JavaScript 2 which he (and others) have been blogging about recently. He also briefly talked about the &#8220;open web&#8221; (WHATWG, W3C, etc) versus a &#8220;closed one&#8221; (Adobe AIR, Microsoft&#8217;s Silverlight, etc), which he has also <a href="http://weblogs.mozillazine.org/roadmap/archives/2007/03/the_open_web_and_its_adversari.html">blogged about previously</a>.</p>
<p>He also talked about some of the language features being proposed for JavaScript 2 which would make it look much more object-oriented (namespaces, classes, packages, generics etc). He said the main drivers for JavaScript 2 were better security, better APIs and better programming language support.</p>
<p>Why are these needed? He felt users deserved more support in the language. He lamented that the combination of Microsoft&#8217;s domination combined with Netscape&#8217;s self-destruction had made the web stagnate. JavaScript hasn&#8217;t really changed that much in those years. As web apps were getting more common place, some of these new features could be more important.</p>
<p>A point he and others have made is that while there are better languages out there, most have not really been used as widely as JavaScript, especially from the kind of wide user base that JavaScript has, so the perceived weaknesses of JavaScript can also be its strengths (something Douglas Crockford looked into further &#8212; more below!).</p>
<p>Update 1: he has posted <a href="http://weblogs.mozillazine.org/roadmap/archives/2007/11/my_media_ajax_keynote.html">slides together with notes and commentary</a>. A useful read.</p>
<p>Update 2: <a href="http://ajaxian.com/archives/brendan-eich-javascript-2-evolution-and-the-myth-busting-tracing-jit">Ajaxian has a decent look at a specific aspect of his talk</a>: JS code bloat and JS2&#8242;s improvement, and the performance benefits of JITting.</p>
<p>(Here&#8217;s a <a href="http://ejohn.org/blog/easy-pdf-sharing/">decent set of slides on the new features being considered in JavaScript 2</a>, actually by John Resig, the next speaker!)</p>
<h3 id="toc-building-interactive-prototypes-with-jquery">Building Interactive Prototypes with jQuery</h3>
<p>By <a href="http://ejohn.org/">John Resig</a>, inventor of <a href="http://jquery.com">jQuery</a>.</p>
<p>I think this was one of my most favourite sessions, but it should not have been! It should not have been because I have been using the excellent jQuery library for about two or three months now, So I should have found most of this talk familiar and therefore not of that much interest.</p>
<p>Instead, I was really impressed with the quality of the session. John was showing the features of jQuery with code examples, and throughout his talk, people from the audience would ask if it was possible to do various things, and he was always able to answer in a polite, positive way, constantly changing his code on the fly in front of everyone. Many of the seemingly complex things that were being asked were implemented not by one line of code, but one word or two!</p>
<p>The talk wasn&#8217;t really about building prototypes, though, more about just using it. (And it isn&#8217;t just for prototyping; it is being used in a lot of big places.)</p>
<p>If you haven&#8217;t seen it, check out the jQuery site and try it out. It&#8217;s really growing on me. While I initially found it weird, it is amazingly powerful, simple, efficient and productive. Its quite different to most of the other popular JavaScript frameworks, especially in how it queries the DOM so efficiently and with hardly any code! I have removed anywhere from 40-60% of some of my JavaScript code when I have used it and I hope to use it more.</p>
<p>Update: <a href="http://ejohn.org/blog/building-interactive-prototypes-with-jquery/">Slides for the JQuery presentation</a> are now available.</p>
<h3 id="toc-metaprogramming-javascript">Metaprogramming JavaScript</h3>
<p>By <a href="http://www.danwebb.net/">Dan Webb</a>, a JavaScript expert and part of the core <a href="http://www.prototypejs.org/">Prototype</a> JavaScript framework team</p>
<p>I had bumped into him the day before during a session break, and he was saying he was nervous about his talk with so many experts as speakers!</p>
<p>But he did a great job explaining a decent topic: meta programming; programming JavaScript to augment itself at run time (e.g. to overcome deficiencies such as IE&#8217;s limited event handling in an efficient manner). Rather than describe the things he talked about, have a look at <a href="http://www.slideshare.net/danwrong/metaprogramming-javascript">his metaprogramming slides</a>.</p>
<h3 id="toc-dojo-1-0-great-experiences-for-everyone">Dojo 1.0: Great Experiences For Everyone</h3>
<p>By <a href="http://alex.dojotoolkit.org/">Alex Russell</a>, project lead for the <a href="http://dojotoolkit.org/">Dojo Toolkit</a></p>
<p>Instead of talking about Dojo, Alex Russell decided to talk about the state of the web in general &#8212; which was a great talk!</p>
<p>Interesting points included that the emergence of Adobe&#8217;s Flex, Microsoft Silverlight, etc signaled a sign of problems for the web; that it may not be evolving much, that it may be hitting the walls of complexity. </p>
<p>He felt that even JSF/JSP (JavaServer Faces and JavaServer Pages) could be a sign of this pain (these technologies use a component-based approach to develop web apps, similar to ASP.NET, so I&#8217;d add that to his concern). His point was that Java developers appear to be afraid of getting their hands dirty with HTML, JavaScript etc, preferring these components to do it instead. Instead, developers <em>do</em> need to care about markup. These same criticisms apply, in my opinion, to ASP.NET. (During the Q &#038; A session just after his talk, a lot of people voiced concerns about Microsoft&#8217;s dominance slowing down change.)</p>
<h3 id="toc-javascript-the-good-parts">JavaScript: The Good Parts</h3>
<p>By <a href="http://www.crockford.com/">Douglas Crockford</a>, Architect at Yahoo! Inc, a well known JavaScript guru who also came up with JSON!</p>
<p>Perhaps one of the two foremost people on JavaScript, this talk was interesting, because Crockford, despite his knowledge of JavaScript is known for being against the proposed ECMAScript 4 specification (which would be implemented as JavaScript 2). He feels that while the additions proposed are interesting and good, it makes the language quite different, and so should be called something other than JavaScript (else he seems to be for it, from what I can tell!).</p>
<p>He has <a href="http://www.jslint.com/lint.html">written previously</a> that, &#8220;JavaScript is a sloppy language, but inside it there is an elegant, better language&#8221;, and that was a point he was trying to make again, quite effectively, I thought.</p>
<p>This talk looked at a number of things problematic with the language and also what worked so well (e.g. lambda functions, closures, the functional programming aspects of JavaScript, the dynamic and flexible nature of the language, etc.)</p>
<p>One annoying (even dangerous) mistake with the JavaScript language he pointed out was semi-colon insertion, whereby if you omitted the &#8220;;&#8221; at the end of a statement, the parser would add it in for you. While this may have been kinda understandable at the time JavaScript came out (to help non-programmers, etc), it had an impact even on code convention:</p>
<p>While in other languages, coding standard/style is typically a matter of preference, here was an example where opening the curly brace on the same line is a MUST for JavaScript:</p>
<pre><code>return
{
    name : value;
}</code></pre>
<p>Is NOT the same as </p>
<pre><code>return {
    name : value;
}</code></pre>
<p>In the first example, because of semi colon insertion, the interpreter will actually do this:</p>
<pre><code>return <strong>;</strong>
{
    name : value;
}</code></pre>
<p>(It will add a semi colon after return!)</p>
<p>Bizarre, but rests the debate on where to open your curly brace for JavaScript!!</p>
<p>He mentioned the tool he wrote a few years ago, <a href="http://www.jslint.com/">JSLint</a>, that checks your JavaScript much like Lint does for C etc (it will catch the above issue, amongst many other things!). Will be worth looking into further and possibly integrating it into our build processes (which they do with Yahoo&#8217;s YUI, for example).</p>
<p>He also made the controversial statement in the panel discussion that followed, that CSS was shit, which didn&#8217;t go down too well! (Though he also said he is not a designer, or something like that!)</p>
<p>The other concern he raised was that IE 6 in particular was holding back the advancement of JavaScript; that changes were hard to introduce because of the prevalence of this poor quality browser.</p>
<h3 id="toc-discussion-panel">Discussion Panel</h3>
<p>Moderated by Jeremy Keith (the guy who coined the term &#8212; and authored a popular book by the same name &#8212; &#8220;DOM Scripting&#8221;)</p>
<p>Brenden Eich, Stuart Langridge, Alex Russell, and Douglas Crockford were on the panel answering questions raised by the audience. Most were around JavaScript&#8217;s future, what frameworks people were using, and concerns about Microsoft&#8217;s domination of the web (its negative impact on the web developer community and whether it mattered any more or not), etc. Some good topics and debates!</p>
<h3 id="toc-conclusion">Conclusion</h3>
<p>A really good day; lots of ideas and details. Some of the powerful aspects of JavaScript were shown in simple terms.</p>
<p>The last @media conference got me excited enough to finally start this blog. This one gives me a sense of urgency to replace some of my JavaScript code with jQuery <img src='http://www.onenaught.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.onenaught.com/posts/37/day-2-media-ajax-november-2007/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Day 1: @media ajax November 2007</title>
		<link>http://www.onenaught.com/posts/36/day1-media-ajax-november-2007</link>
		<comments>http://www.onenaught.com/posts/36/day1-media-ajax-november-2007#comments</comments>
		<pubDate>Thu, 22 Nov 2007 00:04:25 +0000</pubDate>
		<dc:creator>Anup Shah</dc:creator>
				<category><![CDATA[General Web Development]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[@media ajax]]></category>
		<category><![CDATA[ajax]]></category>

		<guid isPermaLink="false">http://www.onenaught.com/posts/36/day1-media-ajax-november-2007</guid>
		<description><![CDATA[<p><img src="/wp-content/uploads/at-media-ajax.gif" alt="@media ajax 2007" class="post-img" align="left" /> My impression of day 1 at @media ajax, the ajax/javascript conference with some of the leading figures in this area.</p>]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.onenaught.com/wp-content/uploads/at-media-ajax.gif" alt="@media ajax 2007" class="post-img" /> So I went to the <a href="http://www.vivabit.com/atmediaAjax/">@media ajax conference</a> earlier this week, and thought I&#8217;d just write up a quick summary of the event/sessions.</p>
<p>This event was one of the premier JavaScript/ajax events including speakers such as Brendan Eich (Mozilla, and inventor of JavaScript), Douglas Crockford (Yahoo, and creator of JSON), Derek Featherstone (Further Ahead), John Resig (jQuery), Jeremy Keith (author of Bulletproof Ajax), and Dion Almaer &#038; Ben Galbraith (Ajaxian).</p>
<p>Every session was of interest. By no means are these a complete set of notes of everything said, just an overview and my impressions of it:</p>
<p><span id="more-36"></span></p>
<h3 id="toc-overall">Overall</h3>
<p>Great. Good to hear from some of the key people in this field. Though the conference felt more about JavaScript than just AJAX (but that was a good thing IMO).</p>
<p>A number of sessions talked of how JavaScript was hated and considered too basic for serious programmers until just recently and yet, without having really changed that much over the 10 years, is now well-respected, incredibly powerful, and very misunderstood!</p>
<h3 id="toc-the-state-of-ajax">The State of AJAX</h3>
<p>By the guys who run <a href="http://ajaxian.com/">Ajaxian</a>.</p>
<p>Interesting talk noting various improvements in just a few short years, and some of the innovative things that are coming, from Mozilla (<a href="http://www.mozilla.org/projects/tamarin/">Tamarin</a>, <a href="http://ajaxian.com/archives/mozilla-announces-screaming-iron-action-monkeys-tamarin-in-ie">Screaming Monkey</a> etc), Google (<a href="http://gears.google.com/">Gears</a>, <a href="http://code.google.com/webtoolkit/">GWT</a>), various frameworks (<a href="http://jquery.com/">JQuery</a>, <a href="http://developer.yahoo.com/yui/">YUI</a>, <a href="http://dojotoolkit.org/">dojo</a>, etc), and of trends such as AJAX on desktop apps (<a href="http://labs.adobe.com/technologies/air/">Adobe AIR</a>, <a href="http://blog.magnetk.com/2007/03/22/joyent-slingshot/">Slingshot</a>, <a href="http://silverlight.net/">Silverlight</a>, <a href="http://labs.mozilla.com/2007/10/prism/">Prism</a> etc).</p>
<p>They <a href="http://www.i-marco.nl/weblog/archive/2006/06/24/time_breakdown_of_modern_web_d">presented a pie chart</a> showing almost 50% of web developer&#8217;s time was typically wasted on sorting out problems with IE/Microsoft! Made people laugh, because how true it unfortunately is. (It was interesting &#8212; though not unexpected &#8212; that in almost every session there was some note, minor or major, of how much Microsoft/IE had stagnated/held back the web.)</p>
<p>Google Gears&#8217; use of worker pools and other features to improve both security and performance was mentioned, which was quite interesting. (Gears has many things being considered for HTML 5 &#8212; including the much-talked about off-line storage &#8212; but because Gears requires a separate install on the user&#8217;s browser, I hadn&#8217;t really given it much attention. I am certainly interested to learn more now.)</p>
<p>The other point they made was that AJAX-based apps were now raising the bar on web apps; from form to function to the &#8220;wow&#8221; factor. They mentioned an interesting usability study looking at two apps with the same functionality, except one just looked better. They asked people around the world (not just US and/or Europe) which one they thought they were more productive with. They all said the better looking one. Whether it was true or not wasn&#8217;t the point; the wow factor was.</p>
<h3 id="toc-but-im-a-bloody-designer">But I&#8217;m a bloody designer!</h3>
<p>Interface designer <a href="http://donotremove.co.uk/">Mike Stenhouse</a> provided the perspective of a designer who, being comfortable on the design/HTML/CSS end of things in the past, perhaps with simple JavaScript stuff (image rollovers etc) would leave the construction and server-side programming to others. However, with web <em>applications</em> much has changed. For example, more programmers are coming to JavaScript and even &#8220;taking JavaScript away from the designer.&#8221;</p>
<p>He talked about how he found himself being more involved in day to day discussions and decisions and that agile development was a good fit for this changing, even for a designer. He found himself being involved both as a customer representative as well as part of the team, even involved in pairing with developers (not to write code necessarily but to appreciate the coding issues and to allow developers to appreciate the design issues).</p>
<p>It was interesting (and good) to hear a designer talking about the merits of <a href="http://en.wikipedia.org/wiki/Test-driven_development">Test Driven Development</a> and even <a href="http://behaviour-driven.org/">Behaviour Driven Development</a>!</p>
<h3 id="toc-real-world-accessibility-for-ajax-enhanced-web-apps">Real World Accessibility for Ajax-enhanced Web Apps</h3>
<p>By accessibility expert, <a href="http://boxofchocolates.ca/">Derek Featherstone</a>.</p>
<p>While he covered techniques that should be reasonably well known now for people who have been following web standards etc for the last few years, he presented it really well so hopefully those not as interested or aware of the issues should be better armed now.</p>
<p>Fundamentally he reiterated that markup still matters; that the structure of the HTML was still fundamental and should come first.</p>
<h3 id="toc-how-to-destroy-the-web">How To Destroy The Web</h3>
<p>By <a href="http://kryogenix.org/">Stuart Langridge</a>, author and one of the founders of the Web Standards Project&#8217;s <a href="http://www.webstandards.org/action/dstf/">DOM Scripting Task Force</a>.</p>
<p>This was a funny, tongue-in-cheek, look at how not to do web development or further the web.</p>
<h3 id="toc-planning-javascript-and-ajax-for-larger-teams">Planning JavaScript and Ajax for Larger Teams</h3>
<p>By <a href="http://wait-till-i.com/">Christian Heilmann</a>, JavaScript expert, now Yahoo! UK lead web developer, standards evangelist and trainer.</p>
<p>Good discussion on the importance of team development. Also made a point that front end stuff like CSS and JavaScript should be treated as application code; with a build process.</p>
<p>Mentioned tools like <a href="http://www.jslint.com/lint.html">JSLint</a> for quality, <a href="http://developer.yahoo.net/blog/archives/2007/07/high_performanc_8.html">minification</a> and consolidation for performance, all things I have been interested in looking into further.</p>
<p>Another decent idea around team motivation and knowledge sharing was the &#8220;lightning talks&#8221; &#8212; 5 minutes to present a problem, 5 minutes demo the solution, 5 minutes to discuss (and then share with the world, through blogs, wikis etc). We have tried hour long sessions with our teams which are really good, but when our development is fully underway, these are sometimes sacrificed, unfortunately. These shorter &#8220;lightning talks&#8221; are an interesting idea, which I hope we try out.</p>
<p>He also talked about architecting JavaScript (thinking of modules instead of pages, providing configuration capabilities, custom events, etc). All good stuff which I have been trying to do more of lately (not always perfectly though), so nice to see that being mentioned.</p>
<h3 id="toc-afternoon-coffee-break">Afternoon Coffee Break</h3>
<p>No, not a session, but a break! The reason this was useful for me was that as a work colleague and I were talking near the cookies and coffee area, Stuart Langridge came over, so I quickly told him I liked his session and we started talking about various things.</p>
<p>He had very briefly mentioned something called Comet which I asked if he could explain further. All he said was, &#8220;why not ask the guy who invented the term&#8221; pointing to another guy just standing right next to us, Alex Russell (one of the speakers for the second day)!</p>
<p>It was a great discussion on the idea behind <a href="http://alex.dojotoolkit.org/?p=545">Comet</a> (rather than the client polling the server continuously for something, being able to push data and events from the server to the client, all while using the existing HTTP infrastructure, which is not built for this type of communication. In short it involves having a script element request a resource from the server, but the server never returning, just blocking until different messages/events/data needs pushing. Simple in idea but involves some complexities to overcome. I will be trying to look into this further.)</p>
<h3 id="toc-ajax-at-work-a-case-study">Ajax at Work: A Case Study</h3>
<p>By Peter-Paul Koch (ppk), known for his useful <a href="http://www.quirksmode.org/">quirksmode</a> web site of tips and tricks and understanding browser incompatibilities.</p>
<p>Ironically for an ajax conference, the only session that actually looked at the technical aspects of ajax. He compared using XML, JSON, CSV, and HTML as the data being returned from an AJAX request, looking at pros and cons of each. (As expected, ultimately XML or JSON are better than CSV or HTML in most cases, but it all depends on the situation.)</p>
<h3 id="toc-conclusion">Conclusion</h3>
<p>So, all in all, a decent day, getting to hear from some well known people. Can&#8217;t say I technically learned much, but I don&#8217;t think that was the goal of the day as such; more to share ideas and connect.</p>
<p><a href="http://www.onenaught.com/posts/37/day-2-media-ajax-november-2007">Day 2 was for the more technical stuff, and had even more well known people talking</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.onenaught.com/posts/36/day1-media-ajax-november-2007/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

