JS Deep Learning-code reuse for callback functions

Source: Internet
Author: User

In JS often back to a code block in multiple places reuse, this practice is not conducive to the optimization of the code, while the maintenance of the latter is also a trouble, if the post-personnel need to modify the reuse of code blocks, often will appear only modify one of them and cause problems, in fact, processing is very simple.

Extract the reusable code block to write a function separately. It's OK to call this function directly elsewhere.

For example, there are two function F1,f2, will execute code block CODE1, we can CODE1 encapsulated into F3,

FUNCITN F1 () {F3} funcitn F2 () {F3}
However, this happens in the actual situation, F1 need to execute F3,F4, and F3 and F4 are Ajax asynchronous commits, but F4 must execute AJAX request in F3, return true. If: The code is as follows:

FUNCITN F1 () {F3F4}

Certainly not, because F3 and F4 are asynchronous requests, F3 has not finished, perhaps F4 has begun to execute, then how to let F4 after the completion of F3 execution.

However, if F3 is restored to a block of code, it can be resolved, but it will not achieve the effect of code reuse. This is all we need to add a callback parameter to the F3.

The specific code is as follows.

function F3 (CallBack) {     $.post ()        . Done (Funciton (result) {          if (result==true&&callback)             CallBack ();        });    }     Funciton F2 () {     F3 (F4)     }}



JS Deep Learning-code reuse for callback functions

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.