Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add some jQuery plugin done callback

my question is how to add to some jQuery pugin like this example...

$('#Div').myPluginLoad();

add done callback like this...

$('#Div').myPluginLoad().done(function(){
    alert('task finished..!!');
});

to execute another function....

in my plugin :

(function ($) {

    $.fn.extend({    
        myPluginLoad: function (options) {    

            //  defaults
            var defaults = {
                padding: 20,
                mouseOverColor: '#000000',
                mouseOutColor: '#ffffff'
            }    
            var options = $.extend(defaults, options);    
            return this.each(function () {    
                /**
                 *    SOME ASYNC TASK
                 **/    
            });
        }
    });
})(jQuery);

Plz, help!!

like image 319
IvanVazquez Avatar asked Feb 26 '26 06:02

IvanVazquez


1 Answers

Something like this should work:

(function ($) {

    $.fn.extend({    
        myPluginLoad: function (options) {    
            var def = $.Deferred();

            //  defaults
            var defaults = {
                padding: 20,
                mouseOverColor: '#000000',
                mouseOutColor: '#ffffff'
            }    
            var options = $.extend(defaults, options);
            var deferredList = [];

            this.each(function () { 
                var innerDef = $.Deferred();
                deferredList.push(innerDef.promise());

                $.ajax({...}) //just for example
                .done(function() {
                    innerDef.resolve();                    
                });
            });

            $.when.apply($, deferredList).done(function() {
               def.resolve(); 
            });

            return def.promise();
        }
    });
})(jQuery);

You would need to create a deferred object to return that represents when all the items have finished loading. You would then need to create another deferred for each iteration of this.each(). When all of those deferreds have been resolved, resolve the one that you returned.

like image 192
Jason P Avatar answered Feb 28 '26 18:02

Jason P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!