Notifying Progressbars With Deferred Objects

Using the jQuery Deferred object to notify progressbar widgets about progress.

by Fernando De Leon

HTML

<div id="progressbar"></div>

CSS

body {
    font-size: 0.8em;
}

JavaScript

(function() {
    
    // Customized progressbar extension.
    $.widget( "app.progressbar", $.ui.progressbar, {
        
        // Constructor. Check if a "deferred" option was passed.
        // If so, setup a proxy handler to the "_notify()" method
        // when progress notifications on the deferred take place.
        _create: function() {
            this._super();
            var deferred = this.options.deferred;
            if ( deferred ) {
                deferred.progress( $.proxy( this, "_notify" ) );
            }
        },
        
        // This is the deferred.progress() handler. Increment the
        // value till the "max" option is reached or exceeded.
        _notify: function() {
            console.log(this.value());
            var value = this.value() || 0,
                max = this.options.max;
            if ( value >= max ) {
                return;
            }
            this.value( value + 1 );
        }
    });

    $(function() {
        
        // Creates a deferred and a progressbar instance. The deferred
        // is passed to the progressbar as an option.
        var dfd = new $.Deferred(),
        $progressbar = $( "#progressbar" ).progressbar({
            deferred: dfd 
        });

        // Bootstrap the update process.
        (function() {
            function update() {
                // Notifying the deferred will increment the
                // progressbar value by 1 until complete.
                dfd.notify();
                setTimeout( update, 100 );   
            }
            setTimeout( update, 3000 );
        })();
        
    });
    
})( jQuery );