<?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>Scriptble &#187; jQuery</title>
	<atom:link href="http://scriptble.com/category/jquery/feed/" rel="self" type="application/rss+xml" />
	<link>http://scriptble.com</link>
	<description>{ js : performance }</description>
	<lastBuildDate>Wed, 01 Feb 2012 20:02:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>jQuery ready, delegate, live!</title>
		<link>http://scriptble.com/2011/03/jquery-ready-delegate-live/</link>
		<comments>http://scriptble.com/2011/03/jquery-ready-delegate-live/#comments</comments>
		<pubDate>Wed, 09 Mar 2011 18:18:51 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[.delegate()]]></category>
		<category><![CDATA[.live()]]></category>
		<category><![CDATA[.ready()]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=177</guid>
		<description><![CDATA[Recently I was browsing through the jQuery subr reddit and noticed this question pop up. Since I am sure this is a pretty common question on "Why won't my jQuery command work properly", I figured I would give a shot at answering it. Hey guys, I'm sure this has been answered before but I can't [...]]]></description>
			<content:encoded><![CDATA[<p>
	Recently I was browsing through the jQuery subr reddit and noticed this question pop up. Since I am sure this is a pretty common question on "Why won't my jQuery command work properly", I figured I would give a shot at answering it.
</p>

<blockquote>
Hey guys, I'm sure this has been answered before but I can't seem to find anything by searching Google or /r/jquery.

I am a beginner with this so forgive me, but I can't find an explanation to this anywhere and I'm curious. When I try to stop the default submit function of a form in the &lt;head&gt; tag of a .html file it won't work, but when I copy and paste the same code into the &lt;body&gt; it works fine. Regardless of where I place it, it is always below the link to the jquery library. This is really confusing and I was hoping you guys could explain this for me. Thanks!

via <a href="http://www.reddit.com/r/jquery/comments/fwtwh/jquery_script_in_body_or_head/">jQuery &lt;script&gt; in &lt;body&gt; or *lt;head&gt;</a>.
</blockquote>

<span id="more-177"></span>
<h2>Problem</h2>
<p>
	Here was a copy of the code that worked:
</p>

<code class="language-javascript">
&lt;html&gt;
	&lt;head&gt;
		&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"&gt;&lt;/script&gt;

	&lt;/head&gt;
	&lt;body&gt;

	&lt;script&gt;
    	$("form").submit(function(){
        	return false;
    		});
	&lt;/script&gt;
	&lt;form id="uriForm" action=""&gt;
		&lt;input type="textbox" name="uriInput" id="uriInput" /&gt;
		&lt;input type="submit" value="submit" id="submit" /&gt;
	&lt;/form&gt;
	&lt;/body&gt;
&lt;/html&gt;
</code>
<br/>
<p>
	However, if he moved the &lt;script&gt; tag into the head, the form submit stopped working.
</p>

<code class="language-javascript">
	&lt;head&gt;
		&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"&gt;&lt;/script&gt;

		&lt;script&gt;
	    	$("form").submit(function(){
	        	return false;
	    		});
		&lt;/script&gt;
	&lt;/head&gt;
</code>
<br/>
<h2>Why?</h2>
<p>
	Why on earth would the first one work, and the second one not? Well, it comes down to when the dom is ready. In the second example, jQuery is looking for a form tag that hasn't been parsed by the browser yet. So it returns an empty jQuery object, to which the submit event is attached.
</p>

<h2>The Fix</h2>
<p>
	We have a couple of ways of fixing this issue. 
</p>

<h3>.ready()</h3>
<p>The .ready() event attached to the BODY tag, will allow us to attach the submit event as soon as the DOM is ready</p>
<code class="language-javascript">
	$(document).ready(function() {
		$("form").submit(function() {
			return false;
		});
	})
</code>
<br/>

<h3>.delegate()</h3>
<p>
	The .delegate() method can be placed anywhere in your page. Since the delegate function will attach the event to any current "form" elements, or any future "form" elements that may appear in the DOM. The gotcha... If you only have one form element on the page, this will work fine. However, IF for some reason, you create another form element, this same event will be attached to that form as well. 
</p>

<code class="language-javascript">
	$(document).delegate("form", function() {
		$("form").submit(function() {
			return false;
		});
	})
</code>
<br/>

<h3>.live()</h3>
<p>
	The .live() method is a variation/alternative of the .delegate() method. However, at least one element must exist before you can use it. Which means, you still need to wrap it in a .ready() or put it in the footer. 
</p>
<blockquote>
	This method is a variation on the basic .bind() method for attaching event handlers to elements. When .bind()  is called, the elements that the jQuery object refers to get the handler attached; elements that get introduced later do not, so they would require another .bind() call. 
</blockquote>


<code class="language-javascript">
	$(document).ready(function() {
		$("form").live("submit", function() {
			return false;
		});
	})
</code>
<br/>

<p>
	In all, either .ready() or .delegate() will work, just make sure you use them properly. You don't want to add another form or other element and have it get an event you hadn't planned on.
</p>]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/03/jquery-ready-delegate-live/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Writing and Updating DOM Elements in a Frame</title>
		<link>http://scriptble.com/2011/02/writing-and-updating-dom-elements-in-a-frame/</link>
		<comments>http://scriptble.com/2011/02/writing-and-updating-dom-elements-in-a-frame/#comments</comments>
		<pubDate>Thu, 17 Feb 2011 00:30:45 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[HTML]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=158</guid>
		<description><![CDATA[Handling writing and updating objects in an iframe can be bothersome in most browsers. Sure things like jQuery tend to help, but not always. A normal way to access a frame in jQuery is below: $("#FRAME").contents() Now, lets say you actually want to get another element inside of the frame, lets get the HEAD element. [...]]]></description>
			<content:encoded><![CDATA[<p>Handling writing and updating objects in an iframe can be bothersome in most browsers. Sure things like jQuery tend to help, but not always.</p>

<p>A normal way to access a frame in jQuery is below:</p>

<code class="language-javascript">
	$("#FRAME").contents()
</code>
<br/>

<p>Now, lets say you actually want to get another element inside of the frame, lets get the HEAD element.</p>

<code class="language-javascript">
	$("#FRAME").contents().find("HEAD");
</code>
<br/>
<span id="more-158"></span>
<p>Awesome, we now have the head element of the document in the frame. Lets add a style tag to it.</p>

<code class="language-javascript">
	$("#FRAME").contents().find("HEAD").append('<style type="text/css">BODY { background-color: green; }</style>');
</code>
<br/>

<p>Now this worked in most browsers... I say most for a reason. This was an actual use case I was trying to accomplish. However, good ole' IE wouldn't let me actually add a DOM element 
anywhere in the frame. The only thing I was able to do was to add in style tags on the elements. So how did I get around it?</p>

<code class="language-javascript">
	var ifrm;
		
	function addElementToFrame(newStyle) {
		if (typeof ifrm == "undefined"){
			ifrm = document.getElementById('previewFrame');
			if (ifrm.contentWindow){
				ifrm = ifrm.contentWindow;
			}else{
				if (ifrm.contentDocument.document){
					ifrm = ifrm.contentDocument.document;
				}else{
					ifrm = ifrm.contentDocument;
				}
			}
		}
		
		/*
		 * Now that we have the document, lets add a new style tag
		 */
		$("HEAD", ifrm.document).append("<style id='tempTag'>" + newStyle + "</style>");
		
	}
</code>
<br/>

<p>Wow, interesting mix of using straight JavaScript and jQuery in there. However, what happens when I want to just update the same style tag with something new?</p>

<code class="language-javascript">
	var ifrm;
		
	function addElementToFrame(newStyle) {
		if (typeof ifrm == "undefined"){
			ifrm = document.getElementById('previewFrame');
			if (ifrm.contentWindow){
				ifrm = ifrm.contentWindow;
			}else{
				if (ifrm.contentDocument.document){
					ifrm = ifrm.contentDocument.document;
				}else{
					ifrm = ifrm.contentDocument;
				}
			}
		}
		
		/*
		 * Now that we have the document, look for an existing style tag
		 */
		var tag = ifrm.document.getElementById("tempTag");
		
		/*
		 * Hmm, this doesn't look right, but it is. IE will not allow you 
		 * to use a pre-existing style tag and set the innerHTML for that 
		 * element. Which means, we can't create the style tag in another
		 * function and pass back the element and then set the innerHTML 
		 * to what we need. Plus, with this limitation, now we need to 
		 * actually remove the style element from the DOM and recreate 
		 * it each time. LAME.
		 */
		if (typeof tag != "undefined" || tag != null){
			$("#tempTag", ifrm.document).remove();
		}
		
		/*
		 * We only have one shot at writing out the style tag, we must 
		 * include the css at that point as well or IE will bail with an
		 * unsuported method exception.
		 *
		 * add a new style tag
		 */
		$("HEAD", ifrm.document).append("<style id='tempTag'>" + newStyle + "</style>");
	}
</code>
<br/>

<p>And that is how you can add new elements to a DOM in an iframe inside of your page.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/02/writing-and-updating-dom-elements-in-a-frame/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Expanding the jQuery Plugin Development Pattern</title>
		<link>http://scriptble.com/2011/02/expanding-the-jquery-plugin-development-pattern/</link>
		<comments>http://scriptble.com/2011/02/expanding-the-jquery-plugin-development-pattern/#comments</comments>
		<pubDate>Tue, 15 Feb 2011 01:00:25 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=151</guid>
		<description><![CDATA[Doing research on a recent project, I came across an article by Mike Alsup on a "jQuery Plugin Development Pattern". If you haven't seen it already its worth a trip to learningjquery.com to checkout the implementation of his pattern. "There are a few requirements that I feel this pattern handles nicely:" Claim only a single [...]]]></description>
			<content:encoded><![CDATA[<p>
	Doing research on a recent project, I came across an article by Mike Alsup on a <a href="http://www.learningjquery.com/2007/10/a-plugin-development-pattern">"jQuery Plugin Development Pattern"</a>. 
	If you haven't seen it already its worth a trip to learningjquery.com to checkout the implementation of his pattern.
</p>

<blockquote>
"There are a few requirements that I feel this pattern handles nicely:"

<ol>
   <li>Claim only a single name in the jQuery namespace</li>
   <li>Accept an options argument to control plugin behavior</li>
   <li>-Provide public access to default plugin settings-</li>
   <li>Provide public access to secondary functions (as applicable)</li>
   <li>Keep private functions private</li>
   <li>Support the Metadata Plugin</li>
   <li>Allow for extending the object via callbacks (either hooks or events) as applicable</li>
   <li>Scope all selectors with the 'this' object</li>
</ol>

</blockquote>
<br/>
<span id="more-151"></span>
<p>
	This is a great start to "authoring a jQuery plugin":http://docs.jquery.com/Plugins/Authoring. However, there are a couple more requirements that I would propse adding in.
</p>

<ol>
   <li>Claim only a single name in the jQuery namespace</li>
   <li>Accept an options argument to control plugin behavior</li>
   <li>-Provide public access to default plugin settings-</li>
   <li>Provide public access to secondary functions (as applicable)</li>
   <li>Keep private functions private</li>
   <li>Support the Metadata Plugin</li>
   <li>**Allow for extending the object via callbacks (either hooks or events) as applicable**</li>
   <li>**Scope all selectors with the 'this' object**</li>
</ol>

<br/>
<p>
	So lets take a look at how we can implement this pattern using a tab plugin.
</p>

<br/>
<h4>Claim Only a single name in the jQuery namespace</h4>
<br/>
<p>
	Setting up a new plugin is pretty simple. First we need to add the plugin name to the jQuery.fn namespace.
</p>

<code class="language-javascript">
	;(function($){
	})(jQuery);
</code>
<br/>
<p>
	Notice that We scope the setup of this plugin inside of an anonymous function that executes with the jQuery parameter as $. We do this so that the jQuery namespace can be changed in order to play well with other 
	javascript frameworks. It also allows us to scope jQuery to $ incase the namespace has already been changed.
</p>

<p>
	Next we need to setup the single namespace for our plugin.
</p>

<code class="language-javascript">
	;(function($){
	    $.fn.tabs = function(tabOptions) {
	        // support mutltiple elements
	        if (this.length > 1){
	            this.each(function() { $(this).tabs(tabOptions) });
	            return this;
			}
        }
	})(jQuery);
</code>
<br/>
<p>
	Notice we setup the name of our plugin into the jQuery.fn namespace. Also, we add in a bit of trickery.  We need to make sure that if this plugin is called on multiple DOM elements, that it will still function properly. 
	We do this by looping through each of the elements and calling .carousel() on them. We then return "this" in order to allow chaining of methods.
</p>

<code class="language-javascript">
        // support mutltiple elements
        if (this.length > 1){
            this.each(function() { $(this).tabs(tabOptions) });
            return this;
		}
</code>
<br/>

<h4>Accept an options argument to control plugin behavior</h4>
<br/>
<p>
	By creating an options argument, we can allow the users to expand/change the default behavior of the plugin. The following code adds in a newOptions parameter and then uses jQuerys 
	built in $.extend to override the default plugin options.
</p>

<code class="language-javascript">
	;(function($){
    $.fn.tabs = function(tabOptions) {
        // support mutltiple elements
        if (this.length > 1){
            this.each(function() { $(this).tabs(tabOptions) });
            return this;
        }

        // SETUP private variabls;
        var tabs = this;

        // setup options
        var defaultOptions = {
								//default options go here.
                                };
								
        var options = $.extend({}, defaultOptions, tabOptions);

        return this;
    }
})(jQuery);

</code>
<br/>
<p>
	Notice the following code it expands the default options:
</p>

<code class="language-javascript">
        var options = $.extend({}, defaultOptions, tabOptions);
</code>
<br/>

<h4>Provide public access to secondary functions (as applicable)</h4>
<br/>
<p>
	We can give access to public functions by attching the functions to the magic variable "this". 
</p>

<code class="language-javascript">
	;(function($){
	    $.fn.tabs = function(tabOptions) {
	        // support mutltiple elements
	        if (this.length > 1){
	            this.each(function() { $(this).tabs(tabOptions) });
	            return this;
	        }
	
	        // SETUP private variabls;
	        var tabs = this;
	
	        // setup options
	        var defaultOptions = {
	                                    debug : false
	                                };
	        var options = $.extend({}, defaultOptions, tabOptions);


			// PUBLIC functions
	        this.changeTab = function() {
	            // change Tab
	        };
	
	        this.getOptions = function() {
	            return options;
	        };

	
	        return this;
	    }
	})(jQuery);

</code>
<br/>

<h4>Keep private functions private</h4>
<br/>
<p>
	Private functions setup in the way below can only be called from within the scope that they were created. What this means is that there is no outside access to these functions. They can only be called 
	from within another public methods or another private methods. In order to access this data we would need to setup public methods to call these private methods.
</p>

<code class="language-javascript">
	;(function($){
	    $.fn.tabs = function(tabOptions) {
	        // support mutltiple elements
	        if (this.length > 1){
	            this.each(function() { $(this).tabs(tabOptions) });
	            return this;
	        }
	
	        // SETUP private variabls;
	        var tabs = this;
	
	        // setup options
	        var defaultOptions = {
	                                    debug : false
	                                };
	        var options = $.extend({}, defaultOptions, tabOptions);

	        // SETUP private functions;
	        var intialize = function() {
					return tabs;
	        };
			
	        var findTabs = function() {
	                                // do something .
	                            };
								
			var selectTab = function(element, tabCSS, selectedClass){
									// do something .
								};
								
	        var hooks = function() {
	                                // do something .
	                            };
			
			// PUBLIC functions
	        this.changeTab = function() {
	            // change Tab
	        };
	
	        this.getOptions = function() {
	            return options;
	        };
	
	        return intialize();
	    }
	})(jQuery);

</code>
<br/>


<h4>Support the Metadata Plugin</h4>
<br/>
<p>Supporting the Metadata plugin is fairly trivial. We test for the existence of the plugin and then add the data that would be attached to the element.</p>

<code class="language-javascript">
	;(function($){
	    $.fn.tabs = function(tabOptions) {
	        // support mutltiple elements
	        if (this.length > 1){
	            this.each(function() { $(this).tabs(tabOptions) });
	            return this;
	        }
	
	        // SETUP private variabls;
	        var tabs = this;
	
	        // setup options
	        var defaultOptions = {
	                                    debug : false
	                                };
	        var options = $.extend({}, defaultOptions, tabOptions);

	        // SETUP private functions;
	        var intialize = function() {
	                // support MetaData plugin
	                if ($.meta){
	                    options = $.extend({}, options, this.data());
	                }

					return tabs;
	        };
			
	        var findTabs = function() {
	                                // do something .
	                            };
								
			var selectTab = function(element, tabCSS, selectedClass){
									// do something .
								};
								
	        var hooks = function() {
	                                // do something .
	                            };
			
			// PUBLIC functions
	        this.changeTab = function() {
	            // change Tab
	        };
	
	        this.getOptions = function() {
	            return options;
	        };
	
	        return intialize();
	    }
	})(jQuery);

</code>
<br/>
<h4>Allow for extending the object via callbacks (either hooks and/or events)</h4>
<br/>
<p>
	In order to do this, lets take a more in depth look at the changeTab function. 
	It sounds complicated, however its a trivial task to setup and allow the moveSlider functionality to be altered by the external options.
</p>

<code class="language-javascript">
	// PUBLIC functions
    this.changeTab = function() {
        // change Tab
    };
</code>
<br/>

<p>In order to alter the behavior we need to allow the user to pass in some options.</p>

<code class="language-javascript">
    // setup options
    var defaultOptions = {
								beforeLoad : function() {
												// do something .
											},
								afterLoad : function() {
												// do something .
											},
                                debug : false
                            };
</code>
<br/>
<p>Now, lets update hooks function to see what needs to be done in order to call the function.</p>

<code class="language-javascript">	   
        var hooks = function(thisObject, hookList, triggerName){
            $(presentation).trigger(triggerName, thisObject);
            if ($.isFunction(hookList)){
                return hookList.apply(thisObject, []).isOK;
            } else if ($.isArray(hookList)) {
                var result = {
                    isOK: true
                };
                for (var i = 0; i < hookList.length; i++) {
                    if (result.isOK) {
                        result = hookList[i].apply(thisObject, [ result.data ]);
                    }
                }
                return result.isOK;
            }else{
                return true;
            }
        }
</code>
<br/>
<p>What exactly is this doing? First of all the hooks function takes 3 parameters. thisObject is equal to the object that you want the callback function to have "this" set to, 
a method to call back on called hookList and the name of the event to be triggered. The reason we call it list, is that we will check to see if hookList is an array of 
functions or just a single function. The following call passes in the tabs object and the onstart callbacks.</p>

<p>Now, lets change the this.changeTab to make use of the beforeLoad and afterLoad events.</p>


<code class="language-javascript">
	this.changeTab = function(element){
		if (hooks(tabs, options.beforeLoad, "beforeLoad")){
			selectTab(element, options.tabsClass, options.tabsSelected);
			
			var tabOptions = {};
			if (options['tab' + tabs.mainTab] != undefined) {
				tabOptions = options['tab' + tabs.mainTab];
			}
			
			$(options.tabPanels, this).hide();
			
			if (options.afterLoad != undefined) {
				hooks(tabs, options.afterLoad, "afterLoad")
			} else {
				$('.tab' + tabs.mainTab, this).show();
			}
		}
	};
</code>
<br/>

<p>In the hooks method we use the .apply in order to pass "this" as the plugin to the next function. They will have access to all of the public methods that are on that instance of the tabs plugin.</p>


<h4>Scope all selectors with the 'this' object</h4>
<br/>
<p>This is actually really simple, but will control the scope of the objects returned by jQuery. Without this, you may clobber another widget on the page or jump outside of the element you are working on. 
Lets take another look at the selectTab method and see how we can scope our selectors.</p>

<code class="language-javascript">
         var selectTab = function(element, tabCSS, selectedClass){
              var selectedTab = 0;
              selectedClass = selectedClass.replace(/^./, "");
              $(tabCSS).each(function(){
                   if (this == element) {
                        tabs.mainTab = selectedTab;
                        $(element).addClass(selectedClass);
                   } else {
                        $(this).removeClass(selectedClass);
                   }
                   selectedTab++;
              });
         };

</code>
<br/>
<p>On the surface, there is nothing wrong with this. However, what happens if we have two different tab groups on the page? Nothing? How about an extremely large DOM? Would this slow down? Yes, actually it would 
and you may or may not be acting on a set of tabs that aren't your own.</p>

<p>So how do we fix this?</p>

<code class="language-javascript">
         var selectTab = function(element, tabCSS, selectedClass){
              var selectedTab = 0;
              selectedClass = selectedClass.replace(/^./, "");
              $(tabCSS, tabs).each(function(){
                   if (this == element) {
                        tabs.mainTab = selectedTab;
                        $(element).addClass(selectedClass);
                   } else {
                        $(this).removeClass(selectedClass);
                   }
                   selectedTab++;
              });
         };
</code>
<br/>
<p>Wait, that is the same code? Close, but look closer at the $(tabCSS) selector. Notice, we now use $(tabCSS, tabs). (<a href="/2011/02/the-great-assumption-javascript/">You could also use $(tabs).find(tabCSS); is faster in most browsers</a>). 
This limits the scope of the search for the tabs and it won't clobber any other tab widgets on the page.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/02/expanding-the-jquery-plugin-development-pattern/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>jQuery 1.5 Deferreds</title>
		<link>http://scriptble.com/2011/02/jquery-1-5-deferreds/</link>
		<comments>http://scriptble.com/2011/02/jquery-1-5-deferreds/#comments</comments>
		<pubDate>Sun, 13 Feb 2011 02:59:18 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Underscore.JS]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=144</guid>
		<description><![CDATA[Eric Hynds on his blog the other day gave a very good run down of jQuery 1.5 Deferreds. From the post: Deferreds, new in jQuery 1.5, decouple logic dependent on the outcome of a task from the task itself. They’re nothing new to the JavaScript scene; Mochikit and Dojo have implemented them for some time, [...]]]></description>
			<content:encoded><![CDATA[</p>
<a href="http://www.erichynds.com/jquery/using-deferreds-in-jquery/">Eric Hynds</a> on his blog the other day gave a very good run down of jQuery 1.5 Deferreds. From the post:
<p>
</br>
<blockquote>Deferreds, new in jQuery 1.5, decouple logic dependent on the outcome of  a task from the task itself.  They’re nothing new to the JavaScript  scene; Mochikit and Dojo have implemented them for some time, but with <a href="http://jaubourg.net/">Julian Aubourg’s</a> AJAX rewrite landing in 1.5, deferreds in jQuery was the logical next  step.  With deferreds, multiple callbacks can be bound to a task’s  outcome, and any of these callbacks can be bound even after the task is  complete.  The task in question may be asynchronous, but not  necessarily.</blockquote>
<br/>
<span id="more-144"></span>
<p>Especially nice is being able to couple multiple statements and once they finish being able to go on to the next step.</p>
<p>In the following example, we retrieve JSON data and a separate template, once the calls finish we move onto rendering them using Underscore.js templating.</p>
</br>
<code class="language-javascript">
var JSONData = {};
var template = "";
function loadData(data){
     JSONData = data;
}

function loadTemplate(data){
     template = data;
}

function render {
     var output = _.template(template, { employeeList : employeeList } );
     $(document.getElementById("output")).html(output);
}

$.when(
     $.getJSON("JSONData").success(loadData), 
     $.get("template.tmpl").success(loadTemplate)
).then(
   render
);
</code>
<br/>
<p>
Deferreds in jQuery is step in the right direction and adds in some very nice functionality to an already feature rich library.
</p>]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/02/jquery-1-5-deferreds/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>$(&#8220;#ID&#8221;) is fast enough</title>
		<link>http://scriptble.com/2011/02/jquery-id-is-fast-enough/</link>
		<comments>http://scriptble.com/2011/02/jquery-id-is-fast-enough/#comments</comments>
		<pubDate>Sat, 12 Feb 2011 22:22:38 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[Do This, Not That]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=129</guid>
		<description><![CDATA[We all know that the fastest selector to use is the ID. Something like $("#id") is better than using a class. However, after looking at the last test we did on The Great Assumption - JavaScript I noticed a large discrepancy in $("#ID") versus the native document.getElementById(). Now, I always assumed it was slower, but [...]]]></description>
			<content:encoded><![CDATA[<section id="assumption">
	<p>
		We all know that the fastest selector to use is the ID. Something like $("#id") is better than using a class. However, 
		after looking at the last test we did on <a href="/2011/02/the-great-assumption-javascript/">The Great Assumption - JavaScript</a> I noticed 
		a large discrepancy in $("#ID") versus the native document.getElementById().
	</p>
	
	<p>
		Now, I always assumed it was slower, but not anywhere near close to what I saw. So, lets challenge the assumption that $("#ID") is good enough.
	</p>
</section>
<span id="more-129"></span>

<section id="testSetup">
	<h3>Setting up the Test</h3>
	<br/>
	<p>
		You can see the test here: <a href="http://jsperf.com/getelement-versus-id">JSPerf $(doc.getElementById()) versus $("#id")</a>
	</p>
	<p>
		I wanted to test 3 of the latest versions of jQuery, same as the last test. I added the following to the test:
	</p>
	
	<code class="language-html">
&lt;script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.min.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
var $15 = jQuery.noConflict();
&lt;/script&gt;

&lt;script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
var $144 = jQuery.noConflict();
&lt;/script&gt;

&lt;script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.2.min.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
var $142 = jQuery.noConflict();
&lt;/script&gt;


&lt;div class="wrapper"&gt;
     &lt;div class="innerWrapper"&gt;
          &lt;div class="button"&gt;
               &lt;a href="javascript:void(0)" id="button" class="buttonRef"&gt;
                    &lt;span class="buttonText"&gt;Text&lt;/span&gt;
               &lt;/a&gt;
          &lt;/div&gt;
     &lt;/div&gt;
&lt;/div&gt;
	</code>
</section>
<br/>

<section id="theTests">
	<h5>The Tests</h5>
	<br/>
	<p>
		So lets setup the actual tests:
	</p>
	
	<code class="language-javascript">
		//getElement - 1.4.2
		$142(document.getElementById("button"));
		
		//ID - 1.4.2
		$142("#button");
		
		
		//getElement - 1.4.4
		$144(document.getElementById("button"));

		//ID - 1.4.2
		$144("#button");
		
		//getElement - 1.5
		$15(document.getElementById("button"));
		
		//ID - 1.4.2
		$15("#button");
	</code>
	<br/>
	<p>
		Each one of the tests above will run and the result will be returned in Ops/Sec. 
	</p>
</section>
<br/>
<section id="Results">
	<h5>Results</h5>
	<br/>
	<p>After runs in all different versions of the browsers we have a fairly good idea of the results. Take a look below.</p>
	<br/>
	<iframe src="http://www.browserscope.org/user/tests/table/agt1YS1wcm9maWxlcnINCxIEVGVzdBien6wEDA?o=html&v=3" style="width: 648px; height: 530px;"></iframe>
</section>
<br/><br/><br/>
<section id="ResultsNative">
	<h5>Native Browser Call Results</h5>
	<br/>
	<img src="/images/hybridID/nativeGetID.png" />
	<br/><br/>
	<p>
		From the last test we know that getting a Node Element from the native browser call is suprisingly efficient and fast in many browsers. Well, that is unless you are using IE 6, 7, 8 or even the beta 9.
	</p>
</section>
<br/>
<section id="ResultsjQuery">
	<h5>jQuery $("#ID") Results</h5>
	<br/>
	<img src="/images/hybridID/jqueryID.png" />
	<br/><br/>
	<p>
		The results from this test show that getting an ID using jQuery is much faster than using the class selector. However, it is way behind the native call.
		The root cause of this is actually due to how the init function is configured. Looking at the source for 1.5, an ID selector will hit 6 IF statements, plus 
		1 regex before it makes the native document.getElementByID(). After the call, there is a series of browser compatibility checks before it assigns the Node 
		Element to the jQuery object and returns.
	</p>
	<code class="language-javascript">
init: function( selector, context ) {
	var match, elem, ret, doc;

	// Handle $(""), $(null), or $(undefined)
	if ( !selector ) {
		return this;
	}

	// Handle $(DOMElement)
	if ( selector.nodeType ) {
		this.context = this[0] = selector;
		this.length = 1;
		return this;
	}
	
	// The body element only exists once, optimize finding it
	if ( selector === "body" && !context && document.body ) {
		this.context = document;
		this[0] = document.body;
		this.selector = "body";
		this.length = 1;
		return this;
	}

	// Handle HTML strings
	if ( typeof selector === "string" ) {
		// Are we dealing with HTML string or an ID?
		match = quickExpr.exec( selector );

		// Verify a match, and that no context was specified for #id
		if ( match && (match[1] || !context) ) {

			// HANDLE: $(html) -> $(array)
			if ( match[1] ) {
				doc = (context ? context.ownerDocument || context : document);

				// If a single string is passed in and it's a single tag
				// just do a createElement and skip the rest
				ret = rsingleTag.exec( selector );

				if ( ret ) {
					if ( jQuery.isPlainObject( context ) ) {
						selector = [ document.createElement( ret[1] ) ];
						jQuery.fn.attr.call( selector, context, true );

					} else {
						selector = [ doc.createElement( ret[1] ) ];
					}

				} else {
					ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
					selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes;
				}
				
				return jQuery.merge( this, selector );
				
			// HANDLE: $("#id")
			} else {
				elem = document.getElementById( match[2] );

				// Check parentNode to catch when Blackberry 4.6 returns
				// nodes that are no longer in the document #6963
				if ( elem && elem.parentNode ) {
					// Handle the case where IE and Opera return items
					// by name instead of ID
					if ( elem.id !== match[2] ) {
						return rootjQuery.find( selector );
					}

					// Otherwise, we inject the element directly into the jQuery object
					this.length = 1;
					this[0] = elem;
				}

				this.context = document;
				this.selector = selector;
				return this;
			}

		// HANDLE: $("TAG")
		} else if ( !context && !rnonword.test( selector ) ) {
			this.selector = selector;
			this.context = document;
			selector = document.getElementsByTagName( selector );
			return jQuery.merge( this, selector );

		// HANDLE: $(expr, $(...))
		} else if ( !context || context.jquery ) {
			return (context || rootjQuery).find( selector );

		// HANDLE: $(expr, context)
		// (which is just equivalent to: $(context).find(expr)
		} else {
			return jQuery( context ).find( selector );
		}

	// HANDLE: $(function)
	// Shortcut for document ready
	} else if ( jQuery.isFunction( selector ) ) {
		return rootjQuery.ready( selector );
	}

	if (selector.selector !== undefined) {
		this.selector = selector.selector;
		this.context = selector.context;
	}

	return jQuery.makeArray( selector, this );
},
	</code>
	<br/>
	<p>
		Notice the elem = document.getElementById( match[2] ) on line 58. This is the part where it delegates its call to the native function.
	</p>
	<p>
		HOWEVER, what is that on line 9? A use case for $(DOMElement)? Why yes, yes it is, and that leads us to the next test.
	</p>
</section>
<br/>
<section id="ResultsHyrbid">
	<h5>Hybrid Results</h5>
	<br/>
	<img src="/images/hybridID/hybrid.png" />
	<br/><br/>
	<p>
		So by selecting the DOM Element, and passing it into to jQuery we have achieved nearly 100% or more increase in speed across all browsers (except IE). IE still benefits from this method, it had a 49% increase 
		in operations per second.
	</p>
</section>
<br/>
<section id="ResultsTogether">
	<h5>Hybrid Results</h5>
	<br/>
	<img src="/images/hybridID/allTogether.png" />
	<br/><br/>
	<p>
		Here you can clearly see that by using a hybrid solution we have achieve a significant amount of gain over using the built 
		in jQuery ID selector. Its not nearly as fast, but allows us to benefit from the built-in functions of jQuery and speed up the 
		operation.
	</p>
</section>
<br/>
<section id="Conclusion">
	<h3>Do This, Not That</h3>
	<br/>
	<p>
		Not exactly what I expected when I set out on this one. However I think we have a clear winner. IF you are using jQuery, pass the node Element in, other wise just use the native getElementById().
	</p>
	<h6>Conclusion</h6>
	<p><strong>Do This</strong></p>
	<code class="language-javascript">
		$(document.getElementById("someId"));
	</code>
	<br/>
	<p><strong>Not That</strong></p>
	<code class="language-javascript">
		$("#someId");
	</code>
</section>]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/02/jquery-id-is-fast-enough/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>The Great Assumption &#8211; Javascript</title>
		<link>http://scriptble.com/2011/02/the-great-assumption-javascript/</link>
		<comments>http://scriptble.com/2011/02/the-great-assumption-javascript/#comments</comments>
		<pubDate>Fri, 11 Feb 2011 04:52:28 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[Do This, Not That]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=115</guid>
		<description><![CDATA[A couple of weeks ago I was sitting down with a Google Frontend Engineer friend of mine, talking about some of the JavaScript best practices we all have come to know and abide by. I found myself in agreement with 90% of everything we were talking about. However, something kept eating at me. Why do [...]]]></description>
			<content:encoded><![CDATA[<section id="greatAssumption">
	<p>
		A couple of weeks ago I was sitting down with a Google Frontend Engineer friend of mine, talking about some of the JavaScript best practices we all have come to know and abide by. I found myself in agreement with 90% of everything we were talking about. However, something kept eating at me. Why do we both agree on these things? Is it because we actually sat down and did some test? Or is more because early in our careers we were told it was the correct way and have never gone about challenging our assumptions.
	</p>
	<p>
		So with this post, I am going to start challenging our assumptions on what's right, OR validate those assumptions with some documented proof. Thus begins our first in a series of posts about performance, and a "Do this, Not that" series. Some of the posts will focus on jQuery, others on core JavaScript, however all of them should give you some insight on what to do in the future.
	</p>
</section>
<span id="more-115"></span>
<br/>
<section id="assumption">
	<h2>Find Versus Context</h2>
	<br/>
	<p>
		Everyone has heard that we should scope our requests in jQuery to make sure and only return results that we are looking for. This is especially true if we are writing a plugin. And lately I have been hearing we should be using .find() to get the elements we are looking for. 
	</p>
	<p>
		Of course, that peaked my interest. Why use .find() which I had heard was slower, than using $("", context) which scopes the call in much the same way in jQuery. So I set off to write a Performance Test that would check to see which one I should be using.
	</p>
</section>

<section id="testSetup">
	<h5>Setting up the Test</h5>
	<br/>
	<p>
		You can see the test here: <a href="http://jsperf.com/jquery-find-versus-context-versions-1-4-2-to-1-5">JSPerf jQuery Find Versus Context versions 1-4-2 to 1-5</a>
	</p>
	<p>
		I wanted to test 3 of the latest versions of jQuery, plus the browsers native docuemnt.getElementById(). so I added the following to the test:
	</p>
	
	<code class="language-html">
		&lt;script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.min.js"&gt;&lt;/script&gt;
		&lt;script type="text/javascript"&gt;
		var $15 = jQuery.noConflict();
		&lt;/script&gt;

		&lt;script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js"&gt;&lt;/script&gt;
		&lt;script type="text/javascript"&gt;
		var $144 = jQuery.noConflict();
		&lt;/script&gt;

		&lt;script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.2.min.js"&gt;&lt;/script&gt;
		&lt;script type="text/javascript"&gt;
		var $142 = jQuery.noConflict();
		&lt;/script&gt;


		&lt;div class="wrapper"&gt;
		     &lt;div class="innerWrapper"&gt;
		          &lt;div class="button"&gt;
		               &lt;a href="javascript:void(0)" id="button" class="buttonRef"&gt;
		                    &lt;span class="buttonText"&gt;Text&lt;/span&gt;
		               &lt;/a&gt;
		          &lt;/div&gt;
		     &lt;/div&gt;
		&lt;/div&gt;
		&lt;script&gt;
		 var context5 = $15("div.wrapper");
		 var context44 = $144("div.wrapper");
		 var context42 = $142("div.wrapper");
		&lt;/script&gt;
	</code>
	<br/>
	<p>
		Notice that I am going to set a variable for each of the individual jQuery versions. This allows me to use multiple version in the noConflict() state. (They won't overwrite each other and I will be able to have all of them on the same page.) Also, I setup a couple of variables that I want to cache the results. If we had to call this for each of the tests, we wouldn't get an accurate result between a find and context search.
	</p>
</section>

<section id="theTests">
	<h5>The Tests</h5>
	<br/>
	<p>
		So lets setup the actual tests:
	</p>
	
	<code class="language-javascript">
	//Get - document
	var item = document.getElementById("button");

	//Get - ID 1.4.2
	var item = $142("#button");

	//Get - ID 1.4.4
	var item = $144("#button");

	//Get - ID 1.5
	var item = $15("#button");

	//Context - ID 1.4.2
	var item = $142("#button", context42);

	//Context - ID 1.4.4
	var item = $144("#button", context44);

	//Context - ID 1.5
	var item = $15("#button", context5);

	//Find - ID 1.4.2
	var item = context42.find("#button")

	//Find - ID 1.4.4
	var item = context44.find("#button")

	//Find - ID 1.5
	var item = context5.find("#button")

	//Get - Class 1.4.2
	var item = $142(".buttonRef");

	//Get - Class 1.4.4
	var item = $144(".buttonRef");

	//Get - Class 1.5
	var item = $15(".buttonRef");

	//Context - Class 1.4.2
	var item = $142(".buttonRef", context42);

	//Context - Class 1.4.4
	var item = $144(".buttonRef", context44);

	//Context - Class 1.5
	var item = $15(".buttonRef", context5);

	//Find - Class 1.4.2
	var item = context42.find(".buttonRef")

	//Find - Class 1.4.4
	var item = context44.find(".buttonRef")

	//Find - Class 1.5
	var item = context5.find(".buttonRef")

	</code>
	<br/>
	<p>
		Each one of the tests above will run and the result will be returned in Ops/Sec. At this point, we are going to run a test to figure out how fast a context.find(""), $("", context) take for an ID and for a class. I also added in a default document.getElementById() to test how fast natively the browser is able to get a Node Element.
	</p>
</section>

<section id="Results">
	<h5>Results</h5>
	<br/>
	<p>After runs in all different versions of the browsers we have a fairly good idea of the results. Take a look below.</p>
	<br/>
	<iframe src="http://www.browserscope.org/user/tests/table/agt1YS1wcm9maWxlcnINCxIEVGVzdBjti6cEDA?o=html&v=3" style="width: 648px; height: 670px;"></iframe>
</section>
<br/><br/><br/>
<section id="ResultsClass">
	<h5>Find a class element Results</h5>
	<br/>
	<img src="/images/findVersusContext/classChart.png" />
	<br/><br/>
	<p>
		In General this test held true. Using find in all but FF3 and Opera is a faster way to find an element using a class.
	</p>
	<h6>Conclusion</h6>
	<p><strong>Do This</strong></p>
	<code class="language-javascript">
		context.find(".someclass");
	</code>
	<br/>
	<p>Not That</p>
	<code class="language-javascript">
		$(".someclass");
	</code>
</section>
<br/>
<section id="ResultsId">
	<h5>Find an element by ID Results</h5>
	<br/>
	<img src="/images/findVersusContext/idChart.png" />
	<br/>
	<br/>
	<p>
		WOW, not what I expected. Not one browse was a find faster than just using $("#someID"). Basically this all boils down to how jQuery treats an ID selector. It doesn't use the sizzle engine to query the Node Element, but uses the browsers built in document.getElementById(). However, if you pass in a context jQuery will use the engine to make sure the element falls within the context you are using.
	</p>
	<h6>Conclusion</h6>
	<p><strong>Do This</strong></p>
	<code class="language-javascript">
		$("#someID");
	</code>
	<br/>
	<p><strong>Not That</strong></p>
	<code class="language-javascript">
		context.find("#someId");
		$("#someId", context);
	</code>
</section>
<br/>
<section id="ResultsId">
	<h5>Find an element using built in getElementById() Results</h5>
	<br/>
	<img src="/images/findVersusContext/byIdChart.png" />
	<br/>
	<br/>
	<p>
		Ok, so this result really confused me after seeing the jQuery $("#someID") results. I wasn't expecting there to be such a discrepancy in operations per second. After seeing this result, I actually started putting together another post. Which will end up the second part of this series.
	</p>
	<p>
		It should be noted that Chrome, Opera, Safari and FF are all doing well over a million operations per second in this area. 
	</p>
</section>
<br/>
<section id="ResultsId">
	<h5>IE breakdown</h5>
	<br/>
	<img src="/images/findVersusContext/ieChart.png" />
	<br/>
	<br/>
	<p>
		After seeing the results above, I thought we needed one more graphic showing the extremely bad numbers IE put up in this test. There was no noticable change between IE6 and IE7, and while IE8 is better, its still bad. However, it looks like the IE9 team is finally taking web development seriously and trying to make some improvements. Of course those improvements still fall WAY short of any of the other browsers on the market.
	</p>
	<p>
		Come on IE team, haven't we learned anything from the IE6 debacle?
	</p>
</section>
<br/>
<section id="conclusion">
	<h5>Conclusion</h5>
	<br/>
	<p>
		Overall, the conlusion here is to never use a context based find/search for an ID. (since there is always only one on the page... right?) If you need to get an element using an ID, just call it via $("#someID").
	</p>
	<p>
		IF you need to get a class element(s), follow this rule:<br/>
		context.find() &gt; $(".someClass", context) &gt; $(".someclass");
	</p>
</section>
<p>
Next Article &gt;&gt; <a href="/2011/02/jquery-id-is-fast-enough/">$(“#ID”) is fast enough</a>
</p>]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/02/the-great-assumption-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Custom Events in jQuery</title>
		<link>http://scriptble.com/2009/05/custom-events-with-jquery/</link>
		<comments>http://scriptble.com/2009/05/custom-events-with-jquery/#comments</comments>
		<pubDate>Thu, 07 May 2009 23:33:44 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=7</guid>
		<description><![CDATA[*quick note: I originally posted this on trulyevil.com. However its time to move sites and actually keep something up and running for a while. Events seem daunting at first, but really jQuery makes them super simple. Events can be used to alter behavior or even have multiple events happen on a single state change. We [...]]]></description>
			<content:encoded><![CDATA[<p>*quick note:  I originally posted this on trulyevil.com. However its time to move sites and actually keep something up and running for a while.</p>

<p>Events seem daunting at first, but really jQuery makes them super simple. Events can be used to alter behavior or even have multiple events happen on a single state change.</p>

<p>We all know about events like click, onkeydown, onmousedown, onmouseover, etc. But you can fire custom events as well. First you need to understand how to fire events. You can do this by using the $().trigger() event through jQuery.</p>

<span id="more-7"></span>
<p>To do this, we will attach an event for the onchange to a select input. Then when the value changes we will fire a custom event called “update”.</p>

<p>First, the select box.</p>

<p>&lt;select name=&#8221;test&#8221; class=&#8221;test&#8221;&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;option value=&#8221; &#8212; &#8220;&gt; &#8212; &lt;/option&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;option value=&#8221; Test 1&#8243;&gt; Test 1&lt;/option&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;option value=&#8221; Test 2&#8243;&gt; Test 2&lt;/option&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;option value=&#8221; Test 3&#8243;&gt; Test 3&lt;/option&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;option value=&#8221; Test 4&#8243;&gt; Test 4&lt;/option&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;option value=&#8221; Test 5&#8243;&gt; Test 5&lt;/option&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;option value=&#8221; Test 6&#8243;&gt; Test 6&lt;/option&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;option value=&#8221; Test 7&#8243;&gt; Test 7&lt;/option&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;option value=&#8221; Test 8&#8243;&gt; Test 8&lt;/option&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;option value=&#8221; Test 9&#8243;&gt; Test 9&lt;/option&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;option value=&#8221; Test 10&#8243;&gt; Test 10&lt;/option&gt;<br />
&lt;/select&gt;</p>


<code class="language-javascript">
$(’select.test’).change( function() { 
     $(’select.test’).trigger(‘update’, $(this).val()); 
});
</code>
<br/>
<p>Now we need to listen to this event, we can do this by using .bind() to listen to events triggered on a DOM element.</p>

<code class="language-javascript">
$(’select.test’).bind(‘update’, function(e, data) { 
     console.log(data);
});
</code>
<br/>

<p>Thats the basic way of firing and listening to custom events in jQuery. We can attach more listeners to the “update” event by attaching them in the same way.</p>

<p>We can also do this in a more OO way. Lets say we have multiple objects/plugins on the page that need to update when the custom event is fired. We can do this by adding the bind code into the object, then when the event is fired we can update our objects.</p>

<code class="language-javascript">
 var object1 = new function() {
     var obj = this;
     this.name = “Object 1″;

     $(’select.test’).bind(‘update’, function(e, data) { obj.update(data); });

     this.update = function(data){
         console.log(“Update from %o with %o”, this, data);
     };

     return this;
 };

 var object2 = new function() {
     var obj = this;
     this.name = “Object 2″;

     $(’select.test’).bind(‘update’, function(e, data) { obj.update(data); });

     this.update = function(data){
         console.log(“Update from %o with %o”, this, data);
     };

     return this;
};
</code>
<br/>

<p>
The console will log the following:<br/>
Update from Object name=Object 1 with ” Test 1″<br/>
Update from Object name=Object 2 with ” Test 1″<br/>
</p>

<p>Currently we have just been passing the value to our update event, BUT you can actually pass more than just the value. You can pass ANY of javascript built in data types, including functions, objects and arrays. If we update the trigger to pass the jQuery object, here is what it would look like:</p>

<code class="language-javascript">
$(’select.test’).change( function() { $(’select.test’).trigger(‘update’, $(this)); } );
</code>
<br/>

<p>
And now our console would log something like the following:<br/>
Update from Object name=Object 1 with &lt;select class=”test” name=”test”&gt;<br/>
Update from Object name=Object 2 with &lt;select class=”test” name=”test"&gt;<br/>
</p>]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2009/05/custom-events-with-jquery/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  scriptble.com/category/jquery/feed/ ) in 0.91142 seconds, on Feb 5th, 2012 at 6:28 pm UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on Feb 5th, 2012 at 7:28 pm UTC -->
