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