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.