<?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>danheberden</title>
	<atom:link href="http://danheberden.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://danheberden.com</link>
	<description>another blog about web stuff</description>
	<lastBuildDate>Sun, 24 Mar 2013 01:04:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>jQuery &#8211; making .then a little more useful</title>
		<link>http://danheberden.com/jquery-making-then-a-little-more-useful-2011-04-02/</link>
		<comments>http://danheberden.com/jquery-making-then-a-little-more-useful-2011-04-02/#comments</comments>
		<pubDate>Sat, 02 Apr 2011 21:09:01 +0000</pubDate>
		<dc:creator>danheberden</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://danheberden.com/?p=117</guid>
		<description><![CDATA[Edit 04.06.2011: This feature is now a part of jQuery 1.6 (commit bb99899c) and called .always. Checkout .chain too! The introduction of Deferreds into jQuery in 1.5 is quite a handy feature. Particularly, being able to make an ajax request and assign callbacks onto the returned jqXHR. However, at least for me, .then doesn&#8217;t work [...]]]></description>
			<content:encoded><![CDATA[<p>Edit 04.06.2011: This feature is now a part of jQuery 1.6 (<a href="https://github.com/jquery/jquery/commit/bb99899ca0de93dd12f5a53f409ff6f72bfcf94c" target="github">commit bb99899c</a>) and called <code>.always</code>. Checkout .chain too! <img src='http://danheberden.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
<p>The introduction of Deferreds into jQuery in 1.5 is quite a handy feature. Particularly, being able to make an ajax request and assign callbacks onto the returned <code>jqXHR</code>.</p>
<p>However, at least for me, .then doesn&#8217;t work the way my brain thinks it should (Thanks to <a href="http://benalman.com">Ben Alman</a> bringing this up). When you get a promise back from the deferred, it has three methods: <code>done</code>, <code>fail</code>, and <code>then</code></p>
<p><code>done</code> and <code>fail</code> do exactly what you&#8217;d think: attach functions to be called if the deferred is resolved or rejected.</p>
</p>
<p><code>then</code> is currently a shortcut method for the two.</p>
<pre class="brush: jscript;">
$.ajax({
    url: 'someUrl'
}).then( doneFn, failFn );
</pre>
<p>The word <u>then</u>, for me, is much more conclusive. It isn&#8217;t a shortcut, it&#8217;s an ultimatum. Thus, I expect <code>.then</code> to work like:</p>
<pre class="brush: jscript;">
$.ajax({
    url: 'someUrl'
}).then( willGetCalledNoMatterWhat );
</pre>
<p>So, if you would rather trade in your shortcut for power, be explicit and have control, or just be part of the cool club &#8211; <s>here&#8217;s how to make .then work the way you want</s> here&#8217;s how to add the functionality yourself. I&#8217;ve been persuaded by Rebecca and Colin to not alter the functionality of an existing, documented method, but rather, add the additional functionally. Their point was simple: by changing the functionality of how somethin existing and documented operates to work contrary the way it should, anyone stepping into code that had modified <code>then</code> would have a hell of a time figuring out why it wasn&#8217;t working to spec.</p>
<pre class="brush: jscript;">
// Wrap in an IIFE and preserve $ incase of $.noConflict();
(function( $ ) {

  // Cache a copy of $.Deferred as it is
  // right now so it can be called later
  var _Deferred = $.Deferred;

  // Overwrite $.Deferred with a new function
  // that takes the same argument
  $.Deferred = function( func ) {

    // Call the original $.Deferred method (the
    // cached copy ) using .apply to assign
    // the same context and send the 'func'
    // argument
    var d = _Deferred.apply( this, func ),
         // copy the created .promise method
         // to duck-punch further down
          _promise = d.promise;

    // add our new 'then' type function, 'always'
    d.always = function( fn ) {
        return d.then( fn, fn );
    };
    // duck-punch the created promise method
    // to use the newly created .always method
    d.promise = function( obj ) {
        var promise = _promise.call( this, obj );
        promise.always = d.always;
        return promise;
    };  

    // return the our modified deferred from
    // _Deferred, but with our new .always
    return d;
  };
})( jQuery );
</pre>
<h4>The Result</h4>
<pre class="brush: jscript;">
$.ajax({
    url: 'someUrl'
}).always( function() {
   /* i get called no matter WHAT */
});
</pre>
<h4>How it works</h4>
<p>This duck-punches the existing <code>$.Deferred</code> function with a wrapper function. $.Deferred creates a new <code>$._Deferred</code> and makes the <code>.then</code>, <code>.done</code>, and <code>.fail</code> methods on the fly. By saving a copy of the old function, we can let it go about its usual business and add the <code>.always</code> function to both the deferred and its promise method.</p>
<h4>Demo</h4>
<p><a href="http://jsfiddle.net/danheberden/FG8uE/" target="jsfiddle">Demo at jsfiddle.net</a></p>
<h4>Smaller Version</h4>
<pre class="brush: jscript;">
(function($){var o=$.Deferred;$.Deferred=function(a){var d=o.apply(this,a),p=d.promise;d.always=function(f){return d.then(f,f);};d.promise=function(j){var n=p.call(this,j);n.always=d.always;return n;};return d;}})(jQuery);
</pre>
]]></content:encoded>
			<wfw:commentRss>http://danheberden.com/jquery-making-then-a-little-more-useful-2011-04-02/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>jQuery Plugin: .serializeForm()</title>
		<link>http://danheberden.com/jquery-plugin-serializeobject-2011-04-01/</link>
		<comments>http://danheberden.com/jquery-plugin-serializeobject-2011-04-01/#comments</comments>
		<pubDate>Fri, 01 Apr 2011 20:18:03 +0000</pubDate>
		<dc:creator>danheberden</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://danheberden.com/?p=110</guid>
		<description><![CDATA[[Update: 2013-03-23. Renamed serializeObject to serializeForm] More often than not, you want an object of your form data to send to the server. I use cakePHP, which makes heavy use of input names like data[ModelName][attribute]. I needed a way to get that same nested format into an object I could send to the server in [...]]]></description>
			<content:encoded><![CDATA[<p>[Update: 2013-03-23. Renamed serializeObject to serializeForm]</p>
<p>More often than not, you want an object of your form data to send to the server. I use cakePHP, which makes heavy use of input names like data[ModelName][attribute]. I needed a way to get that same nested format into an object I could send to the server in an $.ajax call so I made one.</p>
<p>$.fn.serializeForm works on any level of nested array syntax in your element names and creates arrays if items end in [], just like you&#8217;d expect.</p>
<p>For more information and source, check out <a href="https://github.com/danheberden/jquery-serializeForm">my github repo</a>.</p>
<p>For a demo, check out: <a href="http://jsfiddle.net/danheberden/3xcTG/">http://jsfiddle.net/danheberden/3xcTG/</a></p>
<h4>Example document:</h4>
<pre class="brush: xml;">
&lt;div id=&quot;test&quot;&gt;
    &lt;input name=&quot;text1&quot; value=&quot;txt-one&quot; /&gt;
    &lt;input type=&quot;checkbox&quot;
                name=&quot;top[child][]&quot; value=&quot;1&quot; checked=&quot;checked&quot; /&gt;
    &lt;input type=&quot;checkbox&quot;
                name=&quot;top[child][]&quot; value=&quot;2&quot; checked=&quot;checked&quot; /&gt;
    &lt;input type=&quot;checkbox&quot;
                name=&quot;top[child][]&quot; value=&quot;3&quot; checked=&quot;checked&quot; /&gt;

    &lt;select name=&quot;another[select]&quot;&gt;
        &lt;option value=&quot;opt&quot;&gt;&lt;/option&gt;
    &lt;/select&gt;
&lt;/div&gt;
</pre>
<p>Running <code>$( '#test' ).serializeForm()</code> returns:</p>
<pre class="brush: jscript;">
{
  text1: &quot;txt-one&quot;,
  top: {
    child: [ &quot;1&quot;, &quot;2&quot;, &quot;3&quot; ]
  },
  another: {
    select: &quot;opt&quot;
  }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://danheberden.com/jquery-plugin-serializeobject-2011-04-01/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Merging jQuery Deferreds and .animate()</title>
		<link>http://danheberden.com/merging-jquery-deferreds-and-animate-2011-02-13/</link>
		<comments>http://danheberden.com/merging-jquery-deferreds-and-animate-2011-02-13/#comments</comments>
		<pubDate>Sun, 13 Feb 2011 10:19:23 +0000</pubDate>
		<dc:creator>danheberden</dc:creator>
				<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://danheberden.com/?p=72</guid>
		<description><![CDATA[jQuery&#8217;s animate method, and the shorthand methods that use it, are fantastic tools to create animations. Creating animations that link together to achieve a particular effect, and do something specific at the end of the animation, can be a painful, messy task. Luckily, we have .queue() for mashing animations together. But what happens when you [...]]]></description>
			<content:encoded><![CDATA[<p>jQuery&#8217;s animate method, and the shorthand methods that use it, are fantastic tools to create animations. Creating animations that link together to achieve a particular effect, and do something specific at the end of the animation, can be a painful, messy task. Luckily, we have <code>.queue()</code> for mashing animations together.</p>
<p>But what happens when you want bridge the gap between ajax requests and animating? When you want to queue a bunch of animations, get data from the server, and handle it all at once, without a crap-load of nested callbacks? That&#8217;s when <code>jQuery.Deferred()</code> puts on its cape, tightens its utility belt, and saves the day.</p>
<h4>Disclaimer</h4>
<p>I should note, however, that this is more-or-less giving an example of a pending feature request to add deferreds support in <code>$.fn.animate</code>. If the feature request is accepted and landed, it won&#8217;t show up until version 1.6 of jQuery. The principles, however, speak to jQuery&#8217;s flexibility and how to forge its multitude of great features into an even stronger tool.</p>
<p>While this works, its behavior isn&#8217;t consistent with that of jQuery. Namely, the new custom animate method doesn&#8217;t return &#8216;this&#8217;, but a Deferred object. However, that&#8217;s kind of the point of <code>$.sub()</code>: allowing you to copy the jQuery object and have your way with it. So, <em>do</em> try this at home &#8211; just don&#8217;t threaten my life if your site explodes.</p>
<h4>The Demo</h4>
<p>The following demo is a basic, distilled use-case for this kind of situation. Clicking the button opens a div that contains a loading message. While it&#8217;s opening, it is also querying the server for information to populate the box. Once <strong>both</strong> have finished, the loading div is hidden and the box with the retrieved data remains.<br /> <br />
<iframe style="width: 100%; height: 190px" src="http://jsfiddle.net/danheberden/NMh7c/embedded/result,js,html,css"></iframe></p>
<h4>Modifying .animate()</h4>
<p>Here is the code driving the change to <code>.animate()</code></p>
<pre class="brush: jscript;">
// create a sub of jquery (Basically, a copy we can mess with)
var my$ = $.sub();

// make my$ have a modified animate function
my$.fn.animate = function( props, speed, easing, callback ) {
    // from jQuery.speed, forces arguments into props and options objects
    var options = speed &amp;amp;&amp;amp; typeof speed === &amp;quot;object&amp;quot; ?
             jQuery.extend({}, speed) : {
                complete: callback || !callback &amp;amp;&amp;amp; easing ||
                    jQuery.isFunction( speed ) &amp;amp;&amp;amp; speed,
                duration: speed,
                easing: callback &amp;amp;&amp;amp; easing || easing &amp;amp;&amp;amp;
                    !jQuery.isFunction(easing) &amp;amp;&amp;amp; easing
        };

    // create the deferred
    var dfd = my$.Deferred(),
        // a copy of the complete callback
        complete = options.complete,
        // and the count of how many items
        count = this.length;

    // make a new complete function
    options.complete = function() {
        // that calls the old one if it exists
        complete &amp;amp;&amp;amp; complete.call( this );
        // and decrements count and checks if it's 0
        if ( !--count ) {
            // and when it is, resolves the DFD
            dfd.resolve();
        }
    };

    // all the hooks have been made, call the regular animate
    jQuery.fn.animate.call( this, props, options );

    // return the promise that we'll do something
    return dfd.promise();
};
</pre>
<p>While the comments explain just about everything, be sure to read up on <code>$.sub()</code> if you haven&#8217;t already. The new animate function on <code>my$</code> simulates the method signature of the function, <code>$.fn.animate</code>, it&#8217;s attempting to replace. In short, <code>speed</code>, <code>easing</code>, and <code>callback</code> are forced into an options object &mdash; the same as if the second parameter was an object.</p>
<p>The deferred is created, a copy of the complete callback, and the count of how many items. Why? We want to fire the <code>resolve()</code> function on the deferred once <em>all</em> of the animations have finished. The <code>complete()</code> callback is replaced with a wrapper function that calls the original callback and decrements and checks the count. When the count reaches zero, all items have been animated and it&#8217;s safe to fire the <code>resolve()</code> function.</p>
<p>The untouched, standard version of <code>$.fn.animate</code> is called with the same &#8216;this&#8217;, properties, and the modified options object with the new complete wrapper function.</p>
<p>Returned is the promise, <code>dfd.promise()</code>, that lets <code>$.when()</code> do its awesomeness.</p>
<h4>Putting it into action</h4>
<p>If you haven&#8217;t familiarized yourself with deferreds, I highly recommend you read <a href="http://www.erichynds.com/jquery/using-deferreds-in-jquery/" target="eric">Eric Hynds&#8217; fantastic article about it</a>.</p>
<pre class="brush: jscript;">
// retrieves content and updates a dom element
// returns a promise
function populateBox() {
    return $.ajax({
        url: 'your/server/url',
        data: { },
        type: &amp;quot;POST&amp;quot;,
        success: function( data ) {
            $('#content').slideDown().html( data );
        }
    });
}

// the &amp;quot;Get Message&amp;quot; click handler
$('button.load').click( function() {

    // save the button, box and loading as my$ objects
    var $button = my$(this).hide(),
        $box = my$('#box'),
        $loading = my$('.loading');

    // when the functions are done
    $.when(
        // $box was created with my$, so it will
        // use the custom animate function
        $box.slideDown(),
        populateBox()
    // then run the 1st function on success
    // and the second function if either fails
    ).then(
        function() {
            // remove loading, we're done
            $loading.slideUp();
        },
        function() {
            // get that button back here
            $button.show();
            // and hide the box
            $box.slideUp();
        }
    );
});
</pre>
<p>Because the new animate function was created on <code>my$</code>, the copy of jQuery made using <code>$.sub()</code>,  <code>.hide()</code>, <code>.slideUp()</code>, and other helper functions that use the custom <code>.animate()</code> function.</p>
<p>When the animation and ajax request both succeed, thus resolving the promise as <code>true</code>, the first callback function of <code>$.then()</code> is called. However, if one of them fails, the second will be called. You can re-run the demo (by clicking on the run button) and opt to fail the ajax request to see the second function get run. The <code>.then()</code> function is a handy mix of <code>.done()</code> and <code>.fail()</code>, which are useful if you want to provide multiple callbacks.</p>
<h4>Summary</h4>
<p>While I highly doubt this will be <em>the</em> solution to using deferreds with <code>.animate()</code>, I&#8217;m confident it&#8217;ll get the ball rolling. Too, it covers some other topics, such as <code>$.sub()</code>, deferreds, and wrapping functions with alternate behavior, that hopefully you found interesting.</p>
]]></content:encoded>
			<wfw:commentRss>http://danheberden.com/merging-jquery-deferreds-and-animate-2011-02-13/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Duck-punching jQuery UI and the Widget Factory</title>
		<link>http://danheberden.com/duck-punching-jquery-ui-and-the-widget-factory-2011-01-15/</link>
		<comments>http://danheberden.com/duck-punching-jquery-ui-and-the-widget-factory-2011-01-15/#comments</comments>
		<pubDate>Sat, 15 Jan 2011 01:58:21 +0000</pubDate>
		<dc:creator>danheberden</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://danheberden.com/?p=49</guid>
		<description><![CDATA[jQuery UI is a great user-interface library for jQuery. It has some great plugins with a fantastic set of options that allow you to perform all kinds of UI tasks like dialog boxes, tabs, draggable/droppable and more. The CSS framework of jQuery UI is designed to provide an easy path to change the appearance of [...]]]></description>
			<content:encoded><![CDATA[<p>jQuery UI is a great user-interface library for jQuery. It has some great plugins with a fantastic set of options that allow you to perform all kinds of UI tasks like dialog boxes, tabs, draggable/droppable and more. The CSS framework of jQuery UI is designed to provide an easy path to change the appearance of the various widgets and their respective components. </p>
<p>Adjusting the styles and acting on events allows for a great deal of customization. However, some needs simply can&#8217;t be achieved this way. Instead of manually modifying a local copy of jQuery UI and serving that custom version with your web application, a superior route exists using duck-punching and the widget factory.</p>
<p>Duck-punching is a technique of replacing a function so that it still accepts and returns the same variables/options, but operates differently. Duck-punching the functions made available by the widget factory allows the web application to use a CDN copy of jQuery UI and also persist with newer updates. </p>
<p>Our example, the jQuery UI Sortable plugin. </p>
<h3>Demos</h3>
<p>Here&#8217;s how it works now. Re-sort the list using drag and drop.<br />
<iframe style="width: 100%; height: 190px" height="250" src="http://jsfiddle.net/danheberden/6Kt79/embedded/result,js,html,css"></iframe></p>
<p>When you let go of the sortable, though, it instantly snaps into place. Lets make it work like this:<br />
<iframe style="width: 100%; height: 190px" height="250" src="http://jsfiddle.net/danheberden/dYyQn/embedded/result,js,html,css"></iframe></p>
<p>What makes that all possible is taking control over the _mouseStop function inside of the sortable prototype. The widget factory places widgets on <code>$.namespace.widgetName</code> &#8211; in this case, <code>$.ui.sortable</code>. On that object&#8217;s prototype sits those declared functions you see if you browse the jQuery UI source. </p>
<h3>The Finished Product</h3>
<pre class="brush: jscript;">

// save the old _mouseStop function
var _mouseStop = $.ui.sortable.prototype._mouseStop;

// now lets make a new one
$.ui.sortable.prototype._mouseStop = function(){

    // save copies of the current object and args
    var _this = this,
        args = arguments;

    // animate the item to its placeholder
    _this.currentItem.animate( this.placeholder.position(),
            450, &quot;easeOutElastic&quot;, function(){
                // call the original function when it's done
                _mouseStop.apply( _this, args );
            });
}
</pre>
<h3>How it works</h3>
<pre class="brush: jscript;">var _mouseStop = $.ui.sortable.prototype._mouseStop;</pre>
<p>First, a copy of the current function is saved to the var _mouseStop. While we could copy the original function entirely, if it calls other inner functions it can get messy and difficult to manage. This way, the new function can perform whatever operations it wants to and <em>then</em> call the original one.</p>
<pre class="brush: jscript;">$.ui.sortable.prototype._mouseStop = function( event ) {</pre>
<p>Now that the existing function has been saved to _mouseStop, it can be replaced with a new one. </p>
<pre class="brush: jscript;">
 var _this = this,
       args = arguments;</pre>
<p><code>this</code> and <code>arguments</code> will change inside of animate&#8217;s callback function (they are function specific) so is necessary to assign them to variables. </p>
<pre class="brush: jscript;">_this.currentItem.animate( this.placeholder.position(), 450, &quot;easeOutElastic&quot; </pre>
<p>This is where the magic happens. The <code>currentItem</code>, which is the draggable item, is animated to the location of the placeholder element, that is, the element creating the blank space between the li&#8217;s. </p>
<pre class="brush: jscript;">_mouseStop.apply( _this, args );</pre>
<p>Inside of the animation callback function, the original _mouseStop function that was saved in the beginning is called. Using apply, the function can be sent the same <code>this</code> and arguments as the new, modified _mouseStop function.</p>
<p>While this might be a contrived example, I hope the principles of overriding functions on the widget factory came through loud and clear. </p>
]]></content:encoded>
			<wfw:commentRss>http://danheberden.com/duck-punching-jquery-ui-and-the-widget-factory-2011-01-15/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
