• About Me
  • Contact
spacer
  • April 2011
  • February 2011
  • January 2011

jQuery – making .then a little more useful

Published on: 09:04, 02-04-2011 Filed Under: Uncategorized View Comments

Edit 04.06.2011: This feature is now a part of jQuery 1.6 (commit bb99899c) and called .always. Checkout .chain too! spacer

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’t work the way my brain thinks it should (Thanks to Ben Alman bringing this up). When you get a promise back from the deferred, it has three methods: done, fail, and then

done and fail do exactly what you’d think: attach functions to be called if the deferred is resolved or rejected.

then is currently a shortcut method for the two.

$.ajax({
    url: 'someUrl'
}).then( doneFn, failFn );

The word then, for me, is much more conclusive. It isn’t a shortcut, it’s an ultimatum. Thus, I expect .then to work like:

$.ajax({
    url: 'someUrl'
}).then( willGetCalledNoMatterWhat );

So, if you would rather trade in your shortcut for power, be explicit and have control, or just be part of the cool club – here’s how to make .then work the way you want here’s how to add the functionality yourself. I’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 then would have a hell of a time figuring out why it wasn’t working to spec.

// 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 );

The Result

$.ajax({
    url: 'someUrl'
}).always( function() {
   /* i get called no matter WHAT */
});

How it works

This duck-punches the existing $.Deferred function with a wrapper function. $.Deferred creates a new $._Deferred and makes the .then, .done, and .fail methods on the fly. By saving a copy of the old function, we can let it go about its usual business and add the .always function to both the deferred and its promise method.

Demo

Demo at jsfiddle.net

Smaller Version

(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);

jQuery Plugin: .serializeObject()

Published on: 08:04, 01-04-2011 Filed Under: Uncategorized View Comments

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.

$.fn.serializeObject works on any level of nested array syntax in your element names and creates arrays if items end in [], just like you’d expect.

For more information and source, check out my github repo.

For a demo, check out: jsfiddle.net/danheberden/3xcTG/

Example document:

<div id="test">
    <input name="text1" value="txt-one" />
    <input type="checkbox"
                name="top[child][]" value="1" checked="checked" />
    <input type="checkbox"
                name="top[child][]" value="2" checked="checked" />
    <input type="checkbox"
                name="top[child][]" value="3" checked="checked" />

    <select name="another[select]">
        <option value="opt"></option>
    </select>
</div>

Running $( '#test' ).serializeObject() returns:

{
  text1: "txt-one",
  top: {
    child: [ "1", "2", "3" ]
  },
  another: {
    select: "opt"
  }
}

Merging jQuery Deferreds and .animate()

Published on: 10:02, 13-02-2011 Filed Under: jQuery View Comments

jQuery’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 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’s when jQuery.Deferred() puts on its cape, tightens its utility belt, and saves the day.

Disclaimer

I should note, however, that this is more-or-less giving an example of a pending feature request to add deferreds support in $.fn.animate. If the feature request is accepted and landed, it won’t show up until version 1.6 of jQuery. The principles, however, speak to jQuery’s flexibility and how to forge its multitude of great features into an even stronger tool.

While this works, its behavior isn’t consistent with that of jQuery. Namely, the new custom animate method doesn’t return ‘this’, but a Deferred object. However, that’s kind of the point of $.sub(): allowing you to copy the jQuery object and have your way with it. So, do try this at home – just don’t threaten my life if your site explodes.

The Demo

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’s opening, it is also querying the server for information to populate the box. Once both have finished, the loading div is hidden and the box with the retrieved data remains.

Modifying .animate()

Here is the code driving the change to .animate()

// 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; typeof speed === &quot;object&quot; ?
             jQuery.extend({}, speed) : {
                complete: callback || !callback &amp;&amp; easing ||
                    jQuery.isFunction( speed ) &amp;&amp; speed,
                duration: speed,
                easing: callback &amp;&amp; easing || easing &amp;&amp;
                    !jQuery.isFunction(easing) &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; 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();
};

While the comments explain just about everything, be sure to read up on $.sub() if you haven’t already. The new animate function on my$ simulates the method signature of the function, $.fn.animate, it’s attempting to replace. In short, speed, easing, and callback are forced into an options object — the same as if the second parameter was an object.

The deferred is created, a copy of the complete callback, and the count of how many items. Why? We want to fire the resolve() function on the deferred once all of the animations have finished. The complete() 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’s safe to fire the resolve() function.

The untouched, standard version of $.fn.animate is called with the same ‘this’, properties, and the modified options object with the new complete wrapper function.

Returned is the promise, dfd.promise(), that lets $.when() do its awesomeness.

Putting it into action

If you haven’t familiarized yourself with deferreds, I highly recommend you read Eric Hynds’ fantastic article about it.

// retrieves content and updates a dom element
// returns a promise
function populateBox() {
    return $.ajax({
        url: 'your/server/url',
        data: { },
        type: &quot;POST&quot;,
        success: function( data ) {
            $('#content').slideDown().html( data );
        }
    });
}

// the &quot;Get Message&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();
        }
    );
});

Because the new animate function was created on my$, the copy of jQuery made using $.sub(), .hide(), .slideUp(), and other helper functions that use the custom .animate() function.

When the animation and ajax request both succeed, thus resolving the promise as true, the first callback function of $.then() 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 .then() function is a handy mix of .done() and .fail(), which are useful if you want to provide multiple callbacks.

Summary

While I highly doubt this will be the solution to using deferreds with .animate(), I’m confident it’ll get the ball rolling. Too, it covers some other topics, such as $.sub(), deferreds, and wrapping functions with alternate behavior, that hopefully you found interesting.

Duck-punching jQuery UI and the Widget Factory

Published on: 01:01, 15-01-2011 Filed Under: Uncategorized View Comments

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.

Adjusting the styles and acting on events allows for a great deal of customization. However, some needs simply can’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.

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.

Our example, the jQuery UI Sortable plugin.

Demos

Here’s how it works now. Re-sort the list using drag and drop.

When you let go of the sortable, though, it instantly snaps into place. Lets make it work like this:

What makes that all possible is taking control over the _mouseStop function inside of the sortable prototype. The widget factory places widgets on $.namespace.widgetName – in this case, $.ui.sortable. On that object’s prototype sits those declared functions you see if you browse the jQuery UI source.

The Finished Product


// 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, "easeOutElastic", function(){
                // call the original function when it's done
                _mouseStop.apply( _this, args );
            });
}

How it works

var _mouseStop = $.ui.sortable.prototype._mouseStop;

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 then call the original one.

$.ui.sortable.prototype._mouseStop = function( event ) {

Now that the existing function has been saved to _mouseStop, it can be replaced with a new one.

 var _this = this,
       args = arguments;

this and arguments will change inside of animate’s callback function (they are function specific) so is necessary to assign them to variables.

_this.currentItem.animate( this.placeholder.position(), 450, "easeOutElastic" 

This is where the magic happens. The currentItem, 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’s.

_mouseStop.apply( _this, args );

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 this and arguments as the new, modified _mouseStop function.

While this might be a contrived example, I hope the principles of overriding functions on the widget factory came through loud and clear.

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.