Example of jQuery animation promise () method

Source: Internet
Author: User


JQuery's show and hide methods are well known and know that it can accept a callback function for execution after the animation completes. Like what:

$ ('. Js-sam '). Hide (' slow ', function () {
Alert (' You just hid Sam ');
});

However, the JQuery 1.8 version also provides another writing style, namely promise– this Chinese translation is very difficult, now see there is a promise-I still continue to use Promise name. For example code above, we can change this:

var Promisemehidesam = $ ('. Js-sam '). Hide (' slow '). Promise ();

function Whendone () {
Alert (' You just hid Sam ');
}

Promisemehidesam.done (Whendone);

Here, The Promise () method does not pass the argument, and the default is FX, which represents the animation effect.
Promise than Callback (callback), there are a lot of benefits, the most obvious one, we can be completed after the animation to perform all the callback action to deconstruct. Because the Hide function is passed a callback, we can only write all of the actions into the callback, such as:

$ ('. Js-sam '). Hide (' slow ', function () {

Trigger a

Trigger Two

Trigger Three

});

But if it's the Promise:

Func1 () {}
Func2 () {}
Func3 () {}
Promisemehidesam.done (FUNC1);
Promisemehidesam.done (FUNC2);
Promisemehidesam.done (FUNC3);

We can decompose three triggering results into three functions without having to write a large callback function, which is inconvenient to maintain code and is difficult to read.

Another common scenario, for example, is to perform a callback after both animation A and animation B are finished. If the first method of passing the callback function-as I know it, cannot be written. But Promise can:
var animate1 = $ ('. Js-sam '). Hide (). Promise ();
var animate2 = $ ('. Js-hi '). Show (). Promise ();

function Whenbothend () {

Animate1 and Animate2 After the end of execution
Console.log (' Animation all over ');
}

$.when (Animate1, Animate2). Done (Whenbothend);
Very elegant.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.