开发者

Difference between using the new jQuery 1.6 $.animate "promise" and a callback?

See here: http://blog.jquery.com/2011/05/03/jquery-16-released/

What is the difference between this new format:

$(".elements").fadeOut();

$.when( $(".elements") ).done(function( elements ) {
  // all elements faded out
});

and the old:

$(".elements").fadeOut(function() 开发者_JAVA技巧{ /* all elements faded out */});


As Chad said, $.when allows you to pass in a bunch of callbacks and once all of them have completed, done will fire.

http://vimeo.com/22687950 is a video on deferreds and about the 15 minute mark $.when() is introduced. Arround 20 minutes you will see this code:

   var $balls = $(".bounceDemo"),
      a = $balls.eq(0).drop(500),
      b = $balls.eq(1).drop(2000),
      c = $balls.eq(2).drop(4000);
   $.when(a,b,c)
      .done(function(){
          //do something
      });


The only difference that I know of is the $.when().done() syntax allows for multiple callback functions. Whereas many of the "old" methods of passing a callback function take 1 function object.

In your example I could have 5 different functions that are called on .done() instead of just the one callback on animation completion. You could even pass in an array of function objects with the $.when().done() syntax (deferred.done()).


The new format uses deferred objects. They were initially introduced as a more flexible alternative to traditional AJAX callbacks, as they provide higher-level control on callback chaining and resolution.

Deferred objects have proved useful enough that many people wanted to use them to chain animations into their AJAX application logic. Returning a promise from an animate() call was possible but awkward so far. jQuery 1.6 now supports it out of the box.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜