Using jQuery load with promises

后端 未结 5 507
夕颜
夕颜 2020-12-09 03:49

I\'m still trying to wrap my head around deferred and what not, so with this in mind I have a question on how to do the following.

My team and I have 3 separate

5条回答
  •  一整个雨季
    2020-12-09 04:12

    You can store the promise objects in an array and use $.when() to find out if those promises are fullfilled. This could look like this:

    var templates = [ ];
    
    function createPromise( baseInfoTemplate ) {
        return $.Deferred(function( promise ) {
            $('
    ').load(baseInfoTemplate, function() { var baseData = { /* foobar */ }; templates.push( baseData ); promise.resolve(); }); }).promise(); } var myPromises = [ ]; myPromises.push( createPromise( 'some data' ) ); myPromises.push( createPromise( 'even moar data' ) ); myPromises.push( createPromise( 'foo bar heay' ) ); $.when.apply( null, myPromises ).done( function() { templates.forEach(function( template ) { $.tmpl(this, template).appendTo($generalContainer); }); });

    I'm using .apply() here because it accepts an array as arguments for a function call. So basically, we're passing all promises objects to .when().

    Example: http://jsfiddle.net/Hg77A/1/


    Update:

    as Alnitak pointed out, the above example wouldn't make much sense if there is no "success" callback handler. If it is just enough to fire the "all done" handler after you transfered the data with .load(), you just would need to .resolve() the promises within the success handler from .load(). Does that make any sense?

提交回复
热议问题