<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
    <title>Brandon Aaron</title>
    <link>http://brandonaaron.net/</link>
    <description>Mostly about jQuery</description>
    <language>en-us</language>
    <item>
      <title>Event Delegation with jQuery</title>
      <description>&lt;p&gt;jQuery makes implementing event delegation quick and easy! In version 1.4.2 there are now three ways to utilize event delegation: &lt;code&gt;.live()&lt;/code&gt;, &lt;code&gt;.delegate()&lt;/code&gt;, and do-it-yourself. Each technique progressively gives you a little more control and flexibility. Lets take a look at these three techniques with a quick 101 crash course on event delegation&amp;nbsp;first.&lt;/p&gt;

&lt;h3&gt;Event Delegation&amp;nbsp;101&lt;/h3&gt;

&lt;p&gt;At its core event delegation is all about letting events bubble up the &lt;span class="caps"&gt;DOM&lt;/span&gt; tree to a parent element. This provides several advantages such as only binding one event handler instead of potentially 100s and it works with elements currently in the &lt;span class="caps"&gt;DOM&lt;/span&gt; at runtime and those which are injected after&amp;nbsp;runtime.&lt;/p&gt;

&lt;p&gt;Imagine you have a large table of data and you want to do something when the user clicks on a row. You might first start out by binding a click event to each &lt;code&gt;&amp;lt;tr&amp;gt;&lt;/code&gt; which would look like&amp;nbsp;this.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$('tr').bind('click', function(event) {
    // this == tr element
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you have lots and lots of table rows it could take a while to bind all those events. Not to mention the browser now needs to keep track of all those event handlers. Instead, we can use event delegation by binding the click event to the table (or any parent element, maybe even the body) and letting the event bubble up to the table. Then we can inspect the event to see which element was actually clicked on. &lt;em&gt;jQuery either does this for you or makes this part easy and we&amp;#8217;ll look at how to do this in just a&amp;nbsp;moment.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The second reason you might want to use event delegation is for automatically handling dynamic data. Lets say you needed to dynamically add rows to your table. Well, then you&amp;#8217;d have to also bind the click event to those new rows. With event delegation the event is actually bound to the table element and any new rows do not need a new event bound.&amp;nbsp;Awesome!&lt;/p&gt;

&lt;h3&gt;&lt;code&gt;.live()&lt;/code&gt;&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;.live()&lt;/code&gt; method, added in jQuery 1.3, provides the most simple way to implement event delegation and is suitable for simple scenarios. Here is some example code illustrating a click event being captured for all &lt;code&gt;&amp;lt;tr&amp;gt;&lt;/code&gt; elements (old or newly created) on a&amp;nbsp;page.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$('tr').live('click', function(event) {
    // this == tr element
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;You can see this &lt;a href="/examples/event-delegation-with-jquery/1"&gt;example code in action here&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Notice, I said &amp;#8220;page&amp;#8221;. The &lt;code&gt;.live()&lt;/code&gt; method binds events to the document by default. You can actually change this, in jQuery 1.4, by passing in a new context to jQuery. If you are unfamiliar with the context in jQuery, I recommend reading this blog post: &lt;a href="http://brandonaaron.net/blog/2009/06/24/understanding-the-context-in-jquery"&gt;Understanding the Context in jQuery&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;One of the gotchas of this method is that it isn&amp;#8217;t exactly chainable like other jQuery methods. For example if you use a jQuery method that changes the selection of elements, such as &lt;code&gt;.children()&lt;/code&gt; or &lt;code&gt;.parent()&lt;/code&gt;, before calling &lt;code&gt;.live()&lt;/code&gt; then it will not work. In other words, it works best when only used with the given selector. The following code example doesn&amp;#8217;t&amp;nbsp;work.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$('#myContainer').children('table').find('tr').live('click', function(event) {
    /*** does not work! ***/
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You might expect that the previous example would still handle click events for &lt;code&gt;&amp;lt;tr&amp;gt;&lt;/code&gt; elements. However, it isn&amp;#8217;t going to work at all because of the &lt;code&gt;.children()&lt;/code&gt; method. So, &lt;code&gt;.live()&lt;/code&gt; is a simple method for simple&amp;nbsp;scenarios.&lt;/p&gt;

&lt;p&gt;To stop &lt;code&gt;.live()&lt;/code&gt; events, you&amp;#8217;d use the &lt;code&gt;.die()&lt;/code&gt;&amp;nbsp;method.&lt;/p&gt;

&lt;h3&gt;&lt;code&gt;.delegate()&lt;/code&gt;&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;.delegate()&lt;/code&gt; method was introduced in jQuery 1.4.2 and provides a more focused way of doing your event delegation. Keeping with the table example lets look how we can do it with the &lt;code&gt;.delegate()&lt;/code&gt;&amp;nbsp;method.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$('table').delegate('tr', 'click', function(event) {
    // this == tr element
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;You can see this &lt;a href="/examples/event-delegation-with-jquery/2"&gt;example code in action here&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;First off, unlike &lt;code&gt;.live()&lt;/code&gt; events the event handler is actually bound to the selected element (&amp;#8220;table&amp;#8221; in this case). Then the click event is filtered to only fire when the &lt;code&gt;&amp;lt;tr&amp;gt;&lt;/code&gt; was clicked on. This is a great method as it makes it easy to specify (and understand) which element you want to delegate from and which elements to filter the event on. &lt;/p&gt;

&lt;p&gt;This method also clears up the confusion with regards to the chainability that the &lt;code&gt;.live()&lt;/code&gt; method introduced. Here is the example code that didn&amp;#8217;t work with &lt;code&gt;.live()&lt;/code&gt; but does work with&amp;nbsp;delegate.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$(#myContainer').children('table').delegate('tr', 'click', function(event) {
    // this == tr element
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Again, the reason this works and &lt;code&gt;.live()&lt;/code&gt; doesn&amp;#8217;t is because &lt;code&gt;.delegate()&lt;/code&gt; is actually binding the event to the selected parent and then filtering based on the selector passed to the &lt;code&gt;.delegate()&lt;/code&gt;&amp;nbsp;method.&lt;/p&gt;

&lt;p&gt;To stop delegated events, you&amp;#8217;d use the &lt;code&gt;.undelegate()&lt;/code&gt;&amp;nbsp;method.&lt;/p&gt;

&lt;h3&gt;Do-It-Yourself&lt;/h3&gt;

&lt;p&gt;The last technique is the ability to just do-it-yourself. This is for advanced use-cases where you want to have more flexibility than &lt;code&gt;.delegate()&lt;/code&gt; or &lt;code&gt;.live()&lt;/code&gt;. Using a method called &lt;code&gt;.closest()&lt;/code&gt;, which was introduced in jQuery 1.3, we are going to look at the &lt;code&gt;event.target&lt;/code&gt; (which element the event happened on) and see if it or any of its parents are the element we want to filter the event on. Keeping with the table example our code looks like&amp;nbsp;this.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$('table').bind('click', function(event) {
    // this == table element
    var $tr = $(event.target).closest('tr');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;You can see this &lt;a href="/examples/event-delegation-with-jquery/3"&gt;example code in action here&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;As you can see we are just using the good&amp;#8217;ol &lt;code&gt;.bind()&lt;/code&gt; method to bind our click event to the table element directly. Then when the table is clicked we check the &lt;code&gt;event.target&lt;/code&gt; to see if it is the &lt;code&gt;&amp;lt;tr&amp;gt;&lt;/code&gt; or if one of its parents is the &lt;code&gt;&amp;lt;tr&amp;gt;&lt;/code&gt;. If neither of these cases are true then &lt;code&gt;$tr&lt;/code&gt; is an empty jQuery collection. &lt;/p&gt;

&lt;h3&gt;Summary&lt;/h3&gt;

&lt;p&gt;Use &lt;code&gt;.live()&lt;/code&gt; if you just need to add some quick event delegation or handle events on elements that don&amp;#8217;t yet exist in the &lt;span class="caps"&gt;DOM.&lt;/span&gt; Beware though that you shouldn&amp;#8217;t chain &lt;code&gt;.live()&lt;/code&gt; and by default it binds event handlers to the document&amp;nbsp;element.&lt;/p&gt;

&lt;p&gt;Use &lt;code&gt;.delegate()&lt;/code&gt; when you want a little more control and want to chain method&amp;nbsp;calls.&lt;/p&gt;

&lt;p&gt;Use the do-it-yourself technique when you want ultimate control and flexibility with your event&amp;nbsp;delegation.&lt;/p&gt;

&lt;p&gt;Which do you prefer and&amp;nbsp;why?&lt;/p&gt;</description>
      <author>Brandon Aaron</author>
      <pubDate>Thu, 04 Mar 2010 00:06:30 +0000</pubDate>
      <link>http://brandonaaron.net/blog/2010/03/4/event-delegation-with-jquery</link>
      <guid>http://brandonaaron.net/blog/2010/03/4/event-delegation-with-jquery</guid>
    </item>
    <item>
      <title>Special Events: The Changes in 1.4.2</title>
      <description>&lt;p&gt;jQuery&amp;#8217;s event system has seen incredible feature growth over the years and with that growth came some pains. jQuery 1.4.2 included a much needed overhaul of the event system. This also brought some backwards incompatible changes to the two new special event hooks added in 1.4. I &lt;a href="http://brandonaaron.net/blog/2009/06/4/jquery-edge-new-special-event-hooks"&gt;previously blogged&lt;/a&gt; about these two new special event hooks: &lt;code&gt;add&lt;/code&gt; and &lt;code&gt;remove&lt;/code&gt;. These two events hooks brought lots of power by being able to manipulate the event details for each event handler registered. This is different from the existing &lt;code&gt;setup&lt;/code&gt; and &lt;code&gt;teardown&lt;/code&gt; hooks (added in 1.2.2) that only worked once per an event, per an&amp;nbsp;element.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;I&amp;#8217;ve written about Special Events a few times now. I recommend going back and reading the previous posts for more details about Special Events, if you haven&amp;#8217;t already done so. First there was the &lt;a href="http://brandonaaron.net/blog/2009/03/26/special-events"&gt;introductory blog post&lt;/a&gt;, then the post &lt;a href="http://brandonaaron.net/blog/2009/06/4/jquery-edge-new-special-event-hooks"&gt;about the &lt;code&gt;add&lt;/code&gt; and &lt;code&gt;remove&lt;/code&gt; hooks&lt;/a&gt;, and finally a post about &lt;a href="http://brandonaaron.net/blog/2009/06/17/automating-with-special-events"&gt;automating with special events&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;The&amp;nbsp;Changes&lt;/h3&gt;

&lt;p&gt;First lets rundown the changes which at first may seem more complicated than they actually are. It all has to do with how jQuery internally stores the details related to an event per an element (&lt;code&gt;.data('events')&lt;/code&gt;). Since the beginning jQuery stored event details on the handler function itself in an object. Now the event details are stored in an object within an array. This provided several benefits, not the least of these being guaranteed event order in all browsers (which has been a pretty highly desired feature). However, the &lt;code&gt;add&lt;/code&gt; and &lt;code&gt;remove&lt;/code&gt; callback now get the object with the event details passed instead of the individual arguments as before. &lt;/p&gt;

&lt;p&gt;Lets take a look at the two call signatures to make this a little more clear. I&amp;#8217;m going to use the same example that I used in the &lt;a href="http://brandonaaron.net/blog/2009/06/4/jquery-edge-new-special-event-hooks"&gt;previous blog post&lt;/a&gt; about these new event handlers. I&amp;#8217;m only showing the &lt;code&gt;add&lt;/code&gt; and &lt;code&gt;remove&lt;/code&gt; hooks since the &lt;code&gt;setup&lt;/code&gt; and &lt;code&gt;teardown&lt;/code&gt; are&amp;nbsp;unmodified.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// In jQuery 1.4 and 1.4.1
jQuery.event.special.multiclick = {
    add: function( handler, data, namespaces ) {
        // called for each bound handler
    },

    remove: function( namespaces ) {
        // called for each bound handler
    }
};


// In jQuery 1.4.2+
jQuery.event.special.multiclick = {
    add: function( details ) {
        var handler   = details.handler,
            data      = details.data,
            namespace = details.namespace;
    },

    remove: function( details ) {
        var handler   = details.handler,
            data      = details.data,
            namespace = details.namespace;
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;The Updated &lt;code&gt;multiclick&lt;/code&gt; Special&amp;nbsp;Event&lt;/h3&gt;

&lt;p&gt;If you remember the &lt;code&gt;multiclick&lt;/code&gt; event, it had the ability to be configurable per a handler. The usage looks like&amp;nbsp;this.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$('div')
    .bind("multiclick", { threshold: 5 }, function( event ) {
        alert( "Clicked 5 times" );
    })
    .bind("multiclick", { threshold: 3 }, function( event ) {
        alert( "Clicked 3 times" );
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;threshold&lt;/code&gt; passed in the data for the event handler is how many times the element must be clicked before the event handler fires. Most of the functionality for this special event was in the &lt;code&gt;add&lt;/code&gt; hook. It would replace the handler with a handler that would track the number of clicks. Here is what the &lt;code&gt;add&lt;/code&gt; hook for this event looked like&amp;nbsp;before.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;jQuery.event.special.multiclick = {
    add: function( handler, data, namespaces ) {
        // get the required number of clicks from data
        var threshold = data &amp;amp;&amp;amp; data.threshold || 1,
            // number of clicks
            clicks = 0;

        // return a new function that will become the handler
        return function( event ) {
            // increase number of clicks
            clicks += 1;
            if ( clicks === threshold ) {
                // required number of clicks reached, reset
                clicks = 0;
                // call the actual supplied handler
                handler.apply( this, arguments );
            }
        }
    },

    ...
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And here is how it looks in&amp;nbsp;1.4.2.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;jQuery.event.special.multiclick = {
    add: function( details ) {
        var handler   = details.handler,
            data      = details.data,
            threshold = data &amp;amp;&amp;amp; data.threshold || 1,
            clicks    = 0;

        // replace the handler
        details.handler = function(event) {
            // increase number of clicks
            clicks += 1;
            if ( clicks === threshold ) {
              // required number of clicks reached, reset
              clicks = 0;
              // call the actual supplied handler
              handler.apply( this, arguments );
            }
        };
    },

    ...
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The rest of the special event remains the same. Feel free to &lt;a href="/examples/special-events-the-changes-in-1-4-2/1"&gt;take a look at the example&lt;/a&gt; which uses&amp;nbsp;1.4.2.&lt;/p&gt;

&lt;h3&gt;Support&amp;nbsp;1.4+&lt;/h3&gt;

&lt;p&gt;If you need to support 1.4, 1.4.1, and the new way in 1.4.2 then here is some sample code to help you make the transition. This &lt;a href="http://gist.github.com/298508"&gt;sample code&lt;/a&gt; was written by &lt;a href="http://benalman.com/"&gt;Ben Alman&lt;/a&gt; (whom I hear is working on an uber Special Events&amp;nbsp;article).&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// 1.4, 1.4.1 and 1.4.2 (existing plugins, update for 1.4.2 this way)
$.event.special.foo = {

  add: function( handleObj ) {
    // Do something when event is bound here!

    var old_handler;

    function new_handler(event) {
      // Modify event object here!
      old_handler.apply( this, arguments );
    };

    // This may seem a little complicated, but it normalizes the special event
    // .add method between jQuery 1.4/1.4.1 and 1.4.2+
    if ( $.isFunction( handleObj ) ) {
      // 1.4, 1.4.1
      old_handler = handleObj;
      return new_handler;
    } else {
      // 1.4.2+
      old_handler = handleObj.handler;
      handleObj.handler = new_handler;
    }
  }

};
&lt;/code&gt;&lt;/pre&gt;</description>
      <author>Brandon Aaron</author>
      <pubDate>Thu, 25 Feb 2010 04:55:50 +0000</pubDate>
      <link>http://brandonaaron.net/blog/2010/02/25/special-events-the-changes-in-1-4-2</link>
      <guid>http://brandonaaron.net/blog/2010/02/25/special-events-the-changes-in-1-4-2</guid>
    </item>
    <item>
      <title>Connecting the Dots with Web Workers</title>
      <description>&lt;p&gt;A little while back I sat down to experiment with &lt;a href="http://www.whatwg.org/specs/web-workers/current-work/"&gt;Web Workers&lt;/a&gt; and decided I would write a &lt;a href="http://en.wikipedia.org/wiki/Zero-sum"&gt;zero-sum game&lt;/a&gt;. I choose &lt;a href="http://en.wikipedia.org/wiki/Connect_Four"&gt;Connect 4&lt;/a&gt; as the game I&amp;#8217;d use to explore Web Workers with. &lt;em&gt;It helped that I found an algorithm written by Keith Pomakis in &lt;span class="caps"&gt;C.&lt;/span&gt;&lt;/em&gt; First things first, I ported the algorithm to JavaScript and then started my experimentation with Web Workers. I&amp;#8217;d like to share a couple of patterns that helped me when working with Web Workers and then explain a little bit about how I organized the code for the Connect4.js game. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Feel free to go ahead and take a look at the &lt;a href="/code/connect4js/demos"&gt;demo of the Connect4.js game&lt;/a&gt;. It is a demo of the Connect 4 game with the computer playing against itself. I also provide a simple Web Worker &lt;a href="/examples/connecting-the-dots-with-web-workers/1"&gt;example&lt;/a&gt; to base your own projects&amp;nbsp;on.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;Why Web&amp;nbsp;Workers?&lt;/h3&gt;

&lt;p&gt;Essentially Web Workers allow us to offload heavy computations from the main thread. That means our heavy computations will not lock up the browser. In the Connect4.js game the computer will attempt to find the best move by looking ahead several moves (always assuming the other player will make the best move possible). These computations are heavy and time consuming and would normally give the dreaded long running script alert. However, with Web Workers we can just tell our worker to find the best move and let us know when it is&amp;nbsp;done.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Web Worker support is currently quite limited. However, its potential power warrants investigation now, rather than later! The browsers currently supporting Web Workers are: Firefox 3.5+, Safari 4+, and Chrome. I recommend using &lt;a href="http://www.modernizr.com/"&gt;Modernizr&lt;/a&gt; to detect support for modern features such as Web&amp;nbsp;Workers.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;How do they&amp;nbsp;work?&lt;/h3&gt;

&lt;p&gt;A Web Worker is just another JavaScript file that is loaded and executed in a sandbox off the main thread. It has very limited access and can only pass strings. &lt;em&gt;Although, Firefox can pass a &lt;span class="caps"&gt;JSON&lt;/span&gt; object and it will convert it to &lt;span class="caps"&gt;JSON&lt;/span&gt; internally. Lookout for this area of the &lt;span class="caps"&gt;API&lt;/span&gt; to fluctuate some.&lt;/em&gt; To create a new Web Worker you just create a new instance of a &lt;code&gt;Worker&lt;/code&gt; and pass the JavaScript file it should load. &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// create a new worker
var myWorker = new Worker('myworker.js');
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;span class="caps"&gt;API&lt;/span&gt; for communicating with a Web Worker is super simple. There are basically two primary methods used. One for sending messages called &lt;code&gt;postMessage&lt;/code&gt; and one for receiving messages called &lt;code&gt;onmessage&lt;/code&gt;. Using the &lt;code&gt;myWorker&lt;/code&gt; from above we can communicate with it like&amp;nbsp;this.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// Event handler for receiving messages from the worker
myWorker.onmessage = function(event) {
    var data = event.data;
    // do something with the data
};

// method used to send a message to the worker
myWorker.postMessage('my message');
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The worker actually uses the exact same methods itself for communication. So our &lt;code&gt;worker.js&lt;/code&gt; file might look something like&amp;nbsp;this.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// Event handler for receiving messages from the host
onmessage = function(event) {
    var data = event.data;
    // do something with the data
    // ...
    // send a result back to the host
    postMessage('42');
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;For more information about how Web Workers work, I invite you to take a look at the &lt;span class="caps"&gt;MDC&lt;/span&gt; page &lt;a href="https://developer.mozilla.org/En/Using_web_workers"&gt;Using Web Workers&lt;/a&gt;&lt;/em&gt;.&lt;/p&gt;

&lt;h3&gt;Speak&amp;nbsp;&lt;span class="caps"&gt;JSON&lt;/span&gt;&lt;/h3&gt;

&lt;p&gt;It just so happens that the browsers that support Web Workers also have native support for &lt;span class="caps"&gt;JSON.&lt;/span&gt; This is great as it allows us to communicate with the worker using &lt;span class="caps"&gt;JSON.&lt;/span&gt; And that makes it easier for our worker to know which task to execute and with what data. We can use the following &lt;span class="caps"&gt;JSON&lt;/span&gt; format to communicate with our&amp;nbsp;worker.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// data to send a message to the worker
&lt;span class="caps"&gt;JSON&lt;/span&gt;.stringify({
    action: 'sum', // the action to perform
    args: [1, 2]   // the arguments to pass along
});

// data to send back the result from the worker
&lt;span class="caps"&gt;JSON&lt;/span&gt;.stringify({
    action: 'sum',  // the action performed
    returnValue: 3  // the result of the action
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Our worker might look something like this in order to handle the multiple actions and &lt;span class="caps"&gt;JSON.&lt;/span&gt; &lt;em&gt;Albeit with a rather trivial action for the&amp;nbsp;example.&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// available actions to run within the worker
var actions = {
    sum: function(a, b) {
        return a + b;
    }
    // other actions
};

// handle a new request from the host
onmessage = function(event) {
    var data   = &lt;span class="caps"&gt;JSON&lt;/span&gt;.parse(event.data), // parse the data
        action = data.action,            // get the requested action
        args   = data.args,              // get the arguments for the action
        result = { action: action };     // prepare the result

    // if we understand the action
    if (action in actions) {
        // execute the action and set the returnValue
        result.returnValue = actions[action].apply(this, args);
    } else {
        // otherwise set the returnValue to undefined
        result.returnValue = undefined;
    }

    // send back the results as a &lt;span class="caps"&gt;JSON&lt;/span&gt; string
    postMessage(JSON.stringify(result));
};
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Logging from the&amp;nbsp;Worker&lt;/h3&gt;

&lt;p&gt;Since the worker executes in a very limited environment it does not have access to the &lt;code&gt;console&lt;/code&gt; and cannot log messages. However, we can simply add a new action called &lt;code&gt;log&lt;/code&gt; that the host can then use to log the &lt;code&gt;returnValue&lt;/code&gt;. Lets assume our worker sends us a log action via the following&amp;nbsp;&lt;span class="caps"&gt;JSON.&lt;/span&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// a message to log
&lt;span class="caps"&gt;JSON&lt;/span&gt;.stringify({
    action: 'log',
    returnValue: 'the message to log'
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we can handle the &lt;code&gt;log&lt;/code&gt; action just like any other action and just &lt;code&gt;console.log&lt;/code&gt; the data. In the last section we saw what the worker should look like to handle the multiple actions and &lt;span class="caps"&gt;JSON&lt;/span&gt; but now lets look at what the host should look like to handle the multiple actions and&amp;nbsp;&lt;span class="caps"&gt;JSON.&lt;/span&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// avaialble actions to run from the worker
var actions = {
    sum: function(result) {
        // do something with the result
        // maybe publish a custom event
        // or fire a callback
    },
    log: function(message) {
        console.log(message);
    }
};

// create the worker
var myWorker = new Worker('myworker.js');

// handle a response from the worker
myWorker.onmessage = function(event) {
    var data        = &lt;span class="caps"&gt;JSON&lt;/span&gt;.parse(event.data), // parse the data
        action      = data.action,            // get the action
        returnValue = data.returnValue;       // get the returnValue

    // if we understand the action
    if (action in actions) {
        // handle the returnValue for the action
        actions[action].call(this, returnValue);
    } else {
        // throw an error? our worker isn't communicating properly
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Quick&amp;nbsp;Recap&lt;/h3&gt;

&lt;p&gt;So, hopefully that wasn&amp;#8217;t to confusing. Basically, you have a worker that you pass a message to and it should do something with the data and pass a message back to you with the result. We can utilize the &lt;span class="caps"&gt;JSON&lt;/span&gt; format to make interacting with our workers a bit more manageable. Although the example is rather trivial hopefully it provides the structure and information to make it easier to jump start your own web worker project. I&amp;#8217;ve gone ahead and built out the above worker so you can &lt;a href="/examples/connecting-the-dots-with-web-workers/1"&gt;try it for yourself&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;Connect4.js&lt;/h3&gt;

&lt;p&gt;Lets dissect the Connect4.js game to see how it uses Web Workers. The Connect4.js game is actually composed of three different JavaScript files. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Connect4.js - This is the public facing &lt;span class="caps"&gt;API&lt;/span&gt; and behind the scenes uses the patterns described above to communicate with the&amp;nbsp;worker.&lt;/li&gt;
&lt;li&gt;Connect4Worker.js - This is the actual worker file and provides a light-weight interface to the actual game&amp;nbsp;logic.&lt;/li&gt;
&lt;li&gt;Connect4Game.js - This is the actual game logic and is responsible for computing moves and keeping the game state. It is loaded via &lt;code&gt;importScript&lt;/code&gt; from within&amp;nbsp;Connect4Worker.js.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Lets first look at the Connect4Worker.js. Here it is line by line with some&amp;nbsp;comments.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// this method imports another script into the current context
importScripts('Connect4Game.js');

// create a local var to store the game instance
var connect4;

onmessage = function(event) {
    var data   = &lt;span class="caps"&gt;JSON&lt;/span&gt;.parse(event.data), // parse the data
        action = data.action,            // get the action
        args   = data.args,              // get the arguments for the action
        ret    = { action: action };     // prepare the result

    if (action === 'new') {
        // create a new instance 
        connect4 = new Connect4Game(args[0]);
        ret.returnValue = connect4;
    }
    else if (connect4[action]) {
        // perform the action and return the results
        ret.returnValue = connect4[action].apply(connect4, args);
    }
    else {
        // undefined action
        ret.returnValue = { error: 'No method for requested action: ' + action };
    }

    // send the message back
    postMessage(JSON.stringify(ret));
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see it follows the same pattern as described earlier for communicating with the worker. One of the differences is that the actions are actually methods of the &lt;code&gt;connect4&lt;/code&gt; instance. &lt;/p&gt;

&lt;p&gt;For the actual public facing interface I use a simple publish and subscribe pattern (pubsub) to handle the asynchronous behavior. So when I get a response from the worker I publish an event for that particular action. This makes it pretty easy to interact with. Using pubsub I can subscribe multiple functions to the same event. In the demo I use two events: &lt;code&gt;moveend&lt;/code&gt; and &lt;code&gt;gameend&lt;/code&gt;. On &lt;code&gt;moveend&lt;/code&gt; I perform 3 actions. First I visually draw the move in the browser, then I tell the computer to make the next move, and finally if the console is available I log information about the&amp;nbsp;move.&lt;/p&gt;

&lt;p&gt;Lets take a look at a slimmed down version of the game.js file from the demo with some&amp;nbsp;comments.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// create a new game and make the ai a level 5
// the callback is called once the game is all setup
new Connect4({ ai: 5 }, function(game) {
    // draw the move to the screen
    game.subscribe('moveend', drawMove);
    // play the next move
    game.subscribe('moveend', makeNextMove);
    // handle when the game is over
    game.subscribe('gameend', gameOver);

    if ('console' in window) {
        // log some information about the move
        game.subscribe('moveend', logMove);
        // log any debug info
        game.subscribe('debug', debug);
    }

    // make first move
    // autoMove makes the best possible
    // move for the specified player
    // where player 0 is 1 and 1 is 2
    game.autoMove(0);


    function drawMove(player, col, row) { /*...*/ }
    function logMove(player, col, row) { /*...*/ }
    function makeNextMove(player, col, row) { /*...*/ }
    function gameOver() { /*...*/ }
    function debug(obj) { /*...*/ }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the above code when I call &lt;code&gt;game.automove(0)&lt;/code&gt; it is sending a message (via &lt;code&gt;postMessage&lt;/code&gt;) to the Connect4Worker.js and the Connect4Worker.js is then asking the Connect4Game.js to run the &lt;code&gt;automove&lt;/code&gt; method. Once it is finished computing the best move it will send a message back the same way it came with the results of the move. The Connect4Worker.js always passes along the game state as well which the public facing &lt;span class="caps"&gt;API&lt;/span&gt; is then kept in&amp;nbsp;sync.&lt;/p&gt;

&lt;h3&gt;More&amp;nbsp;Distributed&lt;/h3&gt;

&lt;p&gt;There is nothing keeping you from using more than one worker and spawning new workers from within workers. One of the ways I was thinking that the performance could be enhanced is to use multiple workers when computing the best move. This way each potential move could be calculated in parallel if the computer had the resources. It would add some complication to the organization and code structure but might be worth the performance gains especially with a higher &lt;span class="caps"&gt;AI&lt;/span&gt;&amp;nbsp;level.&lt;/p&gt;

&lt;h3&gt;The&amp;nbsp;Demos&lt;/h3&gt;

&lt;p&gt;As mentioned earlier the simple worker I created can be &lt;a href="/examples/connecting-the-dots-with-web-workers/1"&gt;viewed in the browser&lt;/a&gt;. Also, you can see the &lt;a href="/code/connect4js/demos"&gt;demo of the Connect4.js game in action&lt;/a&gt; or you can &lt;a href="http://github.com/brandonaaron/connect4js"&gt;download and/or fork the code&lt;/a&gt; which is on&amp;nbsp;github.&lt;/p&gt;</description>
      <author>Brandon Aaron</author>
      <pubDate>Thu, 18 Feb 2010 08:16:05 +0000</pubDate>
      <link>http://brandonaaron.net/blog/2010/02/18/connecting-the-dots-with-web-workers</link>
      <guid>http://brandonaaron.net/blog/2010/02/18/connecting-the-dots-with-web-workers</guid>
    </item>
    <item>
      <title>Understanding the Context in jQuery</title>
      <description>&lt;p&gt;When selecting elements jQuery has an &lt;a href="http://docs.jquery.com/Core/jQuery#expressioncontext"&gt;optional second argument&lt;/a&gt; called context. This context provides a means to limit the search within a specific node. This is great when you have a very large &lt;span class="caps"&gt;DOM&lt;/span&gt; tree and need to find, for example, all the &lt;code&gt;&amp;lt;a&amp;gt;&lt;/code&gt; tags within a specific part of the &lt;span class="caps"&gt;DOM&lt;/span&gt; tree. I&amp;#8217;ve seen various articles, usually performance related, stating that you should be using a context for your selectors. While it is true that using a context for your selectors can potentially boost performance, most of these articles misuse the&amp;nbsp;context.&lt;/p&gt;

&lt;h3&gt;Finding the&amp;nbsp;Context&lt;/h3&gt;

&lt;p&gt;As of jQuery 1.3 the context is exposed as a property on the jQuery collection. Here is how you can check to see what the context&amp;nbsp;is.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$('a').context; // =&amp;gt; document
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Running the above code shows that the context is the document element. In fact, the default context for all jQuery collections is the document in which jQuery was loaded. In other words, selectors are run against the whole document by&amp;nbsp;default.&lt;/p&gt;

&lt;h3&gt;Changing the&amp;nbsp;Context&lt;/h3&gt;

&lt;p&gt;The context needs to be a node to work properly. This is the part that is often overlooked. I&amp;#8217;ve overlooked it in the past as well. Lots of examples out there tell you to just pass a second selector to jQuery to act as the reference node for the search. While this seems to work, it is still running the search on the whole&amp;nbsp;document.&lt;/p&gt;

&lt;p&gt;Here is an example of passing a second selector as the context. By looking at the &lt;code&gt;context&lt;/code&gt; property you can see that the context is still the document&amp;nbsp;though.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$('a', '#myContainer').context; // =&amp;gt; document
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When jQuery encounters another selector for the context it actually converts it to say the following&amp;nbsp;instead.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$('#myContainer').find('a');
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This conversion also happens the same way if you pass a jQuery collection as the&amp;nbsp;context.&lt;/p&gt;

&lt;p&gt;Now lets actually look at how we can change the context for the jQuery&amp;nbsp;collection.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// get the node for the context
var context = $('#myContainer')[0];

// pass the context as the second argument
$('a', context).context; // =&amp;gt; &amp;lt;div id="myContainer"&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;From this example we can see that passing a node as the second argument actually changes the context for the jQuery&amp;nbsp;collection.&lt;/p&gt;

&lt;h3&gt;jQuery 1.3.3 and&amp;nbsp;.live()&lt;/h3&gt;

&lt;p&gt;In jQuery 1.3.x, the &lt;code&gt;.live()&lt;/code&gt; method binds its event handlers to the document. In the upcoming jQuery 1.3.3 release the &lt;code&gt;.live()&lt;/code&gt; method will bind its  events to the context of the jQuery collection. This means your &lt;code&gt;.live()&lt;/code&gt; events can be more focused and potentially&amp;nbsp;faster.&lt;/p&gt;</description>
      <author>Brandon Aaron</author>
      <pubDate>Wed, 24 Jun 2009 19:20:09 +0000</pubDate>
      <link>http://brandonaaron.net/blog/2009/06/24/understanding-the-context-in-jquery</link>
      <guid>http://brandonaaron.net/blog/2009/06/24/understanding-the-context-in-jquery</guid>
    </item>
    <item>
      <title>Automating with Special Events</title>
      <description>&lt;p&gt;&lt;a href="http://davidwalsh.name/"&gt;David Walsh&lt;/a&gt; had a great idea to coerce an element that is given a click event to have a pointer for its cursor. The pointer is a universal symbol for users to know that something is clickable. Using this technique it would be &amp;#8220;automatic&amp;#8221; that any element given a click event would have a pointer. David set out to use the Special Event hooks within jQuery to make this work. Unfortunately for David those hooks are not widely documented, so his &lt;a href="http://davidwalsh.name/add-events-jquery"&gt;first attempt was unsuccessful&lt;/a&gt;. So, lets see how we can use the Special Event hooks to make this work as&amp;nbsp;desired.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If you haven&amp;#8217;t done so, I recommend reading the &lt;a href="http://brandonaaron.net/blog/2009/03/26/special-events"&gt;Special Events&lt;/a&gt; blog post which explains what special events are and how to use them. In the upcoming jQuery &lt;strike&gt;1.3.3&lt;/strike&gt;1.4 there will be &lt;a href="http://brandonaaron.net/blog/2009/06/4/jquery-edge-new-special-event-hooks"&gt;two more event hooks&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;The Special&amp;nbsp;Event&lt;/h3&gt;

&lt;p&gt;The code, once you understand the Special Event hooks, is fairly straight forward. When a click event is bound to an element, we want to make sure it has a pointer for its cursor. Here is what the code looks like to make this&amp;nbsp;work.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;jQuery.event.special.click = {
    setup: function() {
        jQuery( this ).css( 'cursor', 'pointer' );
        return false;
    },

    teardown: fuction() {
        jQuery( this ).css( 'cursor', '' );
        return false;
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So lets break this small piece of code down. There are two hooks, &lt;code&gt;setup&lt;/code&gt; and &lt;code&gt;teardown&lt;/code&gt;, that are called once per an element. In the &lt;code&gt;setup&lt;/code&gt; hook we add the &lt;span class="caps"&gt;CSS&lt;/span&gt; rule to make the cursor a pointer and in the &lt;code&gt;teardown&lt;/code&gt; hook we revert the change since it is no longer clickable. The &lt;code&gt;teardown&lt;/code&gt; hook is only called after the last click event is&amp;nbsp;unbound.&lt;/p&gt;

&lt;p&gt;The only difference here from David&amp;#8217;s example is the &lt;code&gt;return false&lt;/code&gt; statements in both hooks. The return value in Special Event hooks is particularly important (and easy to overlook). Special Events assume that you will most likely handle the actual binding of the event yourself. In other words, when you don&amp;#8217;t return false jQuery skips the actual native binding (&lt;code&gt;addEventListner&lt;/code&gt; or &lt;code&gt;attachEvent&lt;/code&gt;) of the event to the element. In this particular case we want jQuery to go ahead and run its native binding code so the event is actually registered with the browser. To do this we need to return false from our&amp;nbsp;hooks.&lt;/p&gt;

&lt;h3&gt;Usage&lt;/h3&gt;

&lt;p&gt;Using the same example from David&amp;#8217;s post, the actual usage stays the same. Just bind a click event handler as you normally would using either &lt;code&gt;.bind()&lt;/code&gt; or &lt;code&gt;.click()&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;jQuery( document ).ready(function( $ ) {
    $( '#click-me' ).click(function() {
        var red   = Math.floor( Math.random() * 256 ),
            green = Math.floor( Math.random() * 256 ),
            blue  = Math.floor( Math.random() * 256 ),
            color = 'rgb(' + red + ',' + green + ',' + blue + ')';
        $( this ).css( 'background', color );
    });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can see this in action &lt;a href="/examples/automating-with-special-events/1"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;Enhancement&lt;/h3&gt;

&lt;p&gt;There is one enhancement that I&amp;#8217;d like to recommend. Instead of adding the styles via JavaScript, lets just add a class name instead. Maybe the name could be &amp;#8220;clickable&amp;#8221;. Then we can add a rule in our &lt;span class="caps"&gt;CSS&lt;/span&gt; that says anything with the class of &amp;#8220;clickable&amp;#8221; should have a pointer. This would make it easier to style specific instances of a clickable element. For example, we could add a three pixel blue border to a clickable image. :)  So, the final special event with this enhancement would look like&amp;nbsp;this.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;jQuery.event.special.click = {
    setup: function() {
        jQuery( this ).addClass( 'clickable' );
        return false;
    },

    teardown: fuction() {
        jQuery( this ).removeClass( 'clickable' );
        return false;
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And in our &lt;span class="caps"&gt;CSS&lt;/span&gt; we would need to add a global rule that adds the pointer to &lt;code&gt;.clickable&lt;/code&gt;&amp;nbsp;elements.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;.clickable { cursor: pointer; }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we can specialize our &lt;code&gt;.clickable&lt;/code&gt; class to handle certain elements differently. &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;img.clickable { border: 3px solid blue; cursor: pointer; }
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Last&amp;nbsp;thought&amp;#8230;&lt;/h3&gt;

&lt;p&gt;I had one last thought about this technique. This should not be a replacement for using semantic markup or using progressive enhancement. Most of the time if something should be clickable it should probably be clickable and actually do something when JavaScript is not&amp;nbsp;available.&lt;/p&gt;</description>
      <author>Brandon Aaron</author>
      <pubDate>Wed, 17 Jun 2009 15:44:26 +0000</pubDate>
      <link>http://brandonaaron.net/blog/2009/06/17/automating-with-special-events</link>
      <guid>http://brandonaaron.net/blog/2009/06/17/automating-with-special-events</guid>
    </item>
    <item>
      <title>jQuery Edge: New Special Event Hooks</title>
      <description>&lt;p&gt;&lt;em&gt;These Special Event hooks were changed in 1.4.2. Check out &lt;a href="http://brandonaaron.net/blog/2010/02/25/special-events-the-changes-in-1-4-2"&gt;this blog post&lt;/a&gt; to see the details about the&amp;nbsp;change.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In jQuery &lt;strike&gt;1.3.3&lt;/strike&gt; 1.4 there are two new special event hooks: &lt;code&gt;add&lt;/code&gt; and &lt;code&gt;remove&lt;/code&gt;. These two hooks, unlike &lt;code&gt;setup&lt;/code&gt; and &lt;code&gt;teardown&lt;/code&gt;, are called for each event being bound. The &lt;code&gt;add&lt;/code&gt; hook receives the handler, data, and namespaces as arguments. The &lt;code&gt;remove&lt;/code&gt; hook receives the data and namespaces as arguments. The &lt;code&gt;add&lt;/code&gt; and &lt;code&gt;remove&lt;/code&gt; hooks enable the creation of more complex, even customizable,&amp;nbsp;events.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If you haven&amp;#8217;t done so, I recommend reading the &lt;a href="http://brandonaaron.net/blog/2009/03/26/special-events"&gt;Special Events&lt;/a&gt; blog post which explains what special events are and how to use them. For the following example I assume you already understand the concept of special events in&amp;nbsp;jQuery.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;As an example I&amp;#8217;m going to build a new special event called &amp;#8220;multiclick&amp;#8221;. This event tracks clicks on an element and fires at a given threshold or number of clicks. The required number of clicks will be customizable per a handler. &lt;/p&gt;

&lt;p&gt;First, here is how you&amp;#8217;d use the multiclick&amp;nbsp;event.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$('div')
    .bind("multiclick", { threshold: 5 }, function( event ) {
        alert( "Clicked 5 times" );
    })
    .bind("multiclick", { threshold: 3 }, function( event ) {
        alert( "Clicked 3 times" );
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now lets build it. The skeleton of the multiclick special event looks like&amp;nbsp;this.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;jQuery.event.special.multiclick = {
    add: function( handler, data, namespaces ) {
        // called for each bound handler
    },

    setup: function( data, namespaces ) {
        // called once per an element
    },

    remove: function( namespaces ) {
        // called for each bound handler
    },

    teardown: function( namespaces ) {
        // called once per an element
    },

    handler: function( event ) {

    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Behind the scenes we&amp;#8217;ll need to use a normal click event. We&amp;#8217;ll use the &lt;code&gt;setup&lt;/code&gt; hook to bind the initial click event to track the actual clicks. The &lt;code&gt;handler&lt;/code&gt; method will be used to properly trigger the multiclick events. Once all the multiclick events are removed, the &lt;code&gt;teardown&lt;/code&gt; hook will be triggered. We&amp;#8217;ll need to unbind the the click event we used to track the clicks in the &lt;code&gt;setup&lt;/code&gt; hook. Here is the updated multiclick&amp;nbsp;event.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;jQuery.event.special.multiclick = {
    add: function( handler, data, namespaces ) {
        // called for each bound handler
    },

    setup: function( data, namespaces ) {
        jQuery( this ).bind( "click", jQuery.event.special.multiclick.handler );
    },

    remove: function( namespaces ) {
        // called for each bound handler
    },

    teardown: function( namespaces ) {
        jQuery( this ).unbind( "click", jQuery.event.special.multiclick.handler );
    },

    handler: function( event ) {
        // set correct event type
        event.type = "multiclick";
        // trigger multiclick handlers
        jQuery.event.handle.apply( this, arguments );
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Next we need to make sure the bound function to a multiclick event isn&amp;#8217;t fired until it reaches the number of clicks specified. We&amp;#8217;ll utilize the &lt;code&gt;add&lt;/code&gt; hook for this. The &lt;code&gt;add&lt;/code&gt; hook has the ability to return a function which will take the place of the provided handler. This is a powerful feature and allows us to do all sorts of fun things with special events. In the case of the multiclick event we are going to return a new function that calls the given handler after the specified number of clicks. Here is the &lt;code&gt;add&lt;/code&gt;&amp;nbsp;hook.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;jQuery.event.special.multiclick = {
    add: function( handler, data, namespaces ) {
        // get the required number of clicks from data
        var threshold = data &amp;amp;&amp;amp; data.threshold || 1,
            // number of clicks
            clicks = 0;

        // return a new function that will become the handler
        return function( event ) {
            // increase number of clicks
            clicks += 1;
            if ( clicks === threshold ) {
                // required number of clicks reached, reset
                clicks = 0;
                // call the actual supplied handler
                handler.apply( this, arguments );
            }
        }
    },

    ...
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;add&lt;/code&gt; hook makes use of closures to keep track of the required number of clicks (threshold), the actual number of clicks, and the handler to be called once the required number of clicks is reached. The jQuery event system keeps everything in tact so that when you call unbind with the same named function that you supplied to bind, it still unbinds it as&amp;nbsp;expected.&lt;/p&gt;

&lt;p&gt;It ends up that we don&amp;#8217;t actually need to use the &lt;code&gt;remove&lt;/code&gt; hook for this special event, so we&amp;#8217;ll just remove it. Thats it. The multiclick special event is done. You can see it in action &lt;a href="/examples/jquery-edge-new-special-event-hooks/1"&gt;here&lt;/a&gt; and the complete code&amp;nbsp;follows.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;jQuery.event.special.multiclick = {
    add: function( handler, data, namespaces ) {
        // get the required number of clicks from data
        var threshold = data &amp;amp;&amp;amp; data.threshold || 1,
            // number of clicks
            clicks = 0;

        // return a new function that will become the handler
        return function( event ) {
            // increase number of clicks
            clicks += 1;
            if ( clicks === threshold ) {
                // required number of clicks reached, reset
                clicks = 0;
                // call the actual supplied handler
                handler.apply( this, arguments );
            }
        }
    },

    setup: function( data, namespaces ) {
        jQuery( this ).bind( "click", jQuery.event.special.multiclick.handler );
    },

    teardown: function( namespaces ) {
        jQuery( this ).unbind( "click", jQuery.event.special.multiclick.handler );
    },

    handler: function( event ) {
        // set correct event type
        event.type = "multiclick";
        // trigger multiclick handlers
        jQuery.event.handle.apply( this, arguments );
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Thanks&lt;/h3&gt;

&lt;p&gt;Thanks to &lt;a href="http://blog.threedubmedia.com/"&gt;Mike Helgeson&lt;/a&gt; who helped evolve the special events &lt;span class="caps"&gt;API&lt;/span&gt; to include these two hooks. He also has a handful of special events that he has created: &lt;a href="http://plugins.jquery.com/project/drag"&gt;drag&lt;/a&gt;, &lt;a href="http://plugins.jquery.com/project/drop"&gt;drop&lt;/a&gt;, &lt;a href="http://plugins.jquery.com/project/hover"&gt;hover&lt;/a&gt;, and &lt;a href="http://plugins.jquery.com/project/wheel"&gt;wheel&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;If you knew about the &lt;code&gt;specialAll&lt;/code&gt; event hook, it has been removed in favor of using these two extra&amp;nbsp;hooks.&lt;/em&gt;&lt;/p&gt;</description>
      <author>Brandon Aaron</author>
      <pubDate>Thu, 04 Jun 2009 01:05:18 +0000</pubDate>
      <link>http://brandonaaron.net/blog/2009/06/4/jquery-edge-new-special-event-hooks</link>
      <guid>http://brandonaaron.net/blog/2009/06/4/jquery-edge-new-special-event-hooks</guid>
    </item>
    <item>
      <title>jQuery Edge: Simplified .hover()</title>
      <description>&lt;p&gt;In jQuery &lt;strike&gt;1.3.3&lt;/strike&gt; 1.4 the &lt;code&gt;.hover()&lt;/code&gt; method will optionally accept a single method instead of always requiring two methods. This allows you to contain your logic within one method instead of duplicating it among two. I don&amp;#8217;t know about you but I&amp;#8217;ve avoided using the &lt;code&gt;.hover()&lt;/code&gt; method in favor of just manually binding the mouseenter and mouseleave events so that I could use a single function to handle both events. So, lets look at a typical use-case for&amp;nbsp;hover.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$('li')
    .hover(function(event) {
        $(this).addClass('test');
    }, function(event) {
        $(this).removeClass('test');
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, this is how I&amp;#8217;d typically handle this without the use of &lt;code&gt;.hover()&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$('li')
    .bind('mouseenter mouseleave', function(event) {
        $(this).toggleClass('test');
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now lets use the new functionality of &lt;code&gt;.hover()&lt;/code&gt; instead of manually binding the&amp;nbsp;events.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$('li')
    .hover(function(event) {
        $(this).toggleClass('test');
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Sweet!&lt;/p&gt;

&lt;p&gt;Sometimes though you&amp;#8217;ll need to do more complex interactions than just toggling a class. In these cases you can simply check the event type that is passed to your handler. When the user mouses over, the event type sent to the hover function will be mouseenter. When the user mouses out, the event type sent to the hover function will be mouseleave. Here is an example checking the event&amp;nbsp;type.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$('li')
    .hover(function(event) {
        $(this)[ (event.type == 'mouseenter') ? 'add' : 'remove') + 'Class' ]('test');
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the above example I&amp;#8217;m still just toggling the class on the element that was hovered over/out but doing so in a more verbose way to illustrate how you can check the event&amp;nbsp;type.&lt;/p&gt;</description>
      <author>Brandon Aaron</author>
      <pubDate>Thu, 28 May 2009 16:56:46 +0000</pubDate>
      <link>http://brandonaaron.net/blog/2009/05/28/jquery-edge-simplified-hover</link>
      <guid>http://brandonaaron.net/blog/2009/05/28/jquery-edge-simplified-hover</guid>
    </item>
    <item>
      <title>jQuery Edge: Better Support for other Windows and Documents</title>
      <description>&lt;p&gt;jQuery in the past hasn&amp;#8217;t always played well with other windows and documents than the one it was loaded in. However, jQuery is moving in the right direction to help ease the pain of cross window/frame development. There have been several commits recently that make previously window/document dependent methods, well&amp;#8230; less dependent. So far &lt;code&gt;.bind()&lt;/code&gt;, &lt;code&gt;.css()&lt;/code&gt;, &lt;code&gt;.width()&lt;/code&gt;, and &lt;code&gt;.height()&lt;/code&gt; have all been updated to work with other windows and documents. &lt;/p&gt;

&lt;p&gt;So, how might you use this new found jQuery power? First, if you didn&amp;#8217;t already know jQuery has a method, called &lt;a href="http://docs.jquery.com/Traversing/contents" title="Docs for contents method"&gt;&lt;code&gt;.contents()&lt;/code&gt;&lt;/a&gt;, that when used on an iframe element returns the document of the iframe. &lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// Get a reference to the iframe document
var iframeDoc = $('iframe').contents().get(0);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we can bind an event to it, get the dimensions, get styles of various elements,&amp;nbsp;etc.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// Get width of iframe document
$(iframeDoc).width();

// Get height of iframe document
$(iframeDoc).height();

// Bind event to iframe document
$(iframeDoc).bind('click', function( event ) {
    // do something
});

// Get the style of an element in the iframe
$('div', iframeDoc).css('backgroundColor');
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Simple as&amp;nbsp;that.&lt;/p&gt;</description>
      <author>Brandon Aaron</author>
      <pubDate>Thu, 14 May 2009 11:22:00 +0000</pubDate>
      <link>http://brandonaaron.net/blog/2009/05/14/jquery-edge-better-support-for-other-windows-and-documents</link>
      <guid>http://brandonaaron.net/blog/2009/05/14/jquery-edge-better-support-for-other-windows-and-documents</guid>
    </item>
    <item>
      <title>jQuery Edge: Bind with a Different "this"</title>
      <description>&lt;p&gt;Brand new to jQuery &lt;span class="caps"&gt;SVN&lt;/span&gt; is the oft-requested feature of providing a different value for the &amp;#8220;this&amp;#8221; object in an event callback. Previously jQuery would always send the element as the value of &amp;#8220;this&amp;#8221; in the callback. You can utilize this new feature by passing the object you&amp;#8217;d like to represent &amp;#8220;this&amp;#8221; in the callback as the last argument to either &lt;code&gt;.bind()&lt;/code&gt; or &lt;code&gt;.live()&lt;/code&gt;. Lets look at some example&amp;nbsp;code!&lt;/p&gt;

&lt;p&gt;The typical use-case for this functionality is that you&amp;#8217;ll have an object (or a class) and you want to call a method of that class when you click on a particular element. However, the &amp;#8220;this&amp;#8221; object inside the method will be set to the element the event happened on. Usually in these situations you&amp;#8217;d want the &amp;#8220;this&amp;#8221; object to represent the instance of your class, not the element. Here is an example that tries to illustrate this&amp;nbsp;use-case.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// Create a class
var MyClass = function() {
    // initialize the class
    this.clicked = false;
    this.element = null;
};
MyClass.prototype.click = function( event ) {
    // handle the click event on an element
    // the "this" object should represent the instance of
    // the class, not the element the event happened on.
    // the element can be retreived using the event.target
    // or event.currentTarget

    // set the clicked property to true
    this.clicked = true;

    // set the element property to the element that was clicked
    this.element = event.target;

    // cancel the event
    return false;
};

// Create an instance of MyClass
var myInstance = new MyClass();

// Bind an event that calls the click method of myInstance
// and make sure the "this" object is set to myInstance
$("li").live("click", myInstance.click, myInstance);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see from the example code the actual element the event happened on can still be retrieved via the &lt;code&gt;event.target&lt;/code&gt; or &lt;code&gt;event.currentTarget&lt;/code&gt; properties. Both of these properties are normalized/fixed to work cross-browser (as is the &lt;code&gt;event.relatedTarget&lt;/code&gt; property). In the example above I used the &lt;code&gt;live&lt;/code&gt; method of binding events but the same applies for the &lt;code&gt;bind&lt;/code&gt;&amp;nbsp;method.&lt;/p&gt;</description>
      <author>Brandon Aaron</author>
      <pubDate>Tue, 12 May 2009 10:50:00 +0000</pubDate>
      <link>http://brandonaaron.net/blog/2009/05/12/jquery-edge-bind-with-a-different-this</link>
      <guid>http://brandonaaron.net/blog/2009/05/12/jquery-edge-bind-with-a-different-this</guid>
    </item>
    <item>
      <title>jQuery Edge: Live Events now with Data</title>
      <description>&lt;p&gt;In jQuery &lt;strike&gt;1.3.3&lt;/strike&gt; 1.4 the &lt;code&gt;.live()&lt;/code&gt; method will have the ability to pass data along just like you might do with &lt;code&gt;.bind()&lt;/code&gt;. The &lt;code&gt;.bind()&lt;/code&gt; (and now &lt;code&gt;.live()&lt;/code&gt;) method takes an optional second argument called &amp;#8220;data&amp;#8221;. The data can then be accessed within the event handler by using the &lt;code&gt;event.data&lt;/code&gt; property. Here is what the code would look like to use this&amp;nbsp;feature.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// The data
var eventConfig = {
    selectedClass: "selected"
};

$("li").live("click", eventConfig, function( event ) {
    // Retreive selectedClass from the event data
    var selectedClass = event.data.selectedClass;

    // Toggle the class amongst the siblings
    $(this).addClass( selectedClass )
        .siblings().removeClass( selectedClass );
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So in the previous example, trivial as it may be, each time you click an &amp;#8220;li&amp;#8221; element the selected class defined in the &lt;code&gt;eventConfig&lt;/code&gt; is assigned to the clicked element and removed from the&amp;nbsp;siblings.&lt;/p&gt;</description>
      <author>Brandon Aaron</author>
      <pubDate>Fri, 08 May 2009 10:22:00 +0000</pubDate>
      <link>http://brandonaaron.net/blog/2009/05/8/jquery-edge-live-events-now-with-data</link>
      <guid>http://brandonaaron.net/blog/2009/05/8/jquery-edge-live-events-now-with-data</guid>
    </item>
  </channel>
</rss>
