Home Web Front-end JS Tutorial How to customize a callback function in jQuery

How to customize a callback function in jQuery

Jun 16, 2017 pm 02:59 PM
jquery function how customize

First of all, from the literal translation of callback "callback", we can understand that this is a mechanism for function calls.

When we encounter a noun, we may first search on Baidu and Google to see how the official explanation is

The following is the definition of callback from Wikipedia:

a callback is a piece of executable code that is passed as an argument to other code which is expected to call back (execute) the argument at some convenient time

Hard translation: A callback function is an executable code segment that is used as a parameter of another function. This code segment is executed at a convenient time.

Popular explanation: Treat function f2 as a The parameters are passed to function f1 and f2 is executed at the appropriate time in f1 (I use f1, f2 in all the examples below)

So we can get a callback function pattern like this

1

2

3

4

function f1(f2) {    //f1要执行的一些代码

    if (f2 && typeof(f2) === "function") { //对f2做判断是否存在并且是一个函数        f2();

    }

}

Copy after login

It should be noted here that f2 in the two parameters is a pointer to the function f2, so f2 cannot be followed by brackets

, and f2 inside f1 must be followed by brackets because at this time we need to call and execute f2, so we must write f2()

Let’s instantiate this pattern and see its execution results

1

2

3

4

5

6

7

8

9

声明函数function f1(f2) {

alert("我是f1");if (f2 && typeof(f2) === "function") { //写上判断是个好习惯f2()

}

}

执行

f1(function() {

alert("我是f2");

})

结果://"我是f1",“我是f2”

Copy after login

Let’s look at the entire function execution process. When calling f1(function(){alert("I am f2 ");})

First pass an anonymous function to f1(), and this anonymous function is the parameter f2 in the declared function. The javascript program is executed from top to bottom. Alert("I It's f1"); and then executed f2();

Can we write it like this?

1

2

3

4

5

6

7

8

function f1(f2) {    alert("我是f1");    if (f2 && typeof(f2) === "function") { 

        f2()

    }    alert("我又是f1 哈哈");

}

执行

f1(function(){

    alert("我是f2");

})//结果:我是f1 ,我是f2,我又是1 哈哈

Copy after login

Looking at the definition of callback, we can make the callback execute when we want to Execution does not affect the execution flow of f1 itself

But for encapsulation and beauty, most of us will write it like this

1

2

3

4

5

function f1(f2){

if (f2 && typeof(f2) === "function") { 

settimeOut(function(){f2()},1000) ;//f1执行1s后f2执行}

}function f2(){/**/}

f1(f2);

Copy after login

In fact, the callback function is not that complicated. In js, you can treat function as a Ordinary parameters. As long as () is added after it, it means calling this function.

Look at the following example again

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

$(function(){

    function funcname(param){

        //do something

          

        //callback

        param.callback();   

    }

  

    //调用

    funcname({

        callback:function(){

            alert('callback do');

        }  

    });     

});

Copy after login

It can also be seen from the above example that in fact, every time a function is defined, the function is added to the stack of the container, and the index is the function name. The default is under window, so you can throw the string there, and you can also call this callback function through the string under window.

If you have parameters, you can use the above method.

For example, an example in jQuery

1

2

3

$("#div1").fadeOut("fast",functin(){

    $("#div2").fadeIn("slow");

})

Copy after login

Let #div be quickly hidden and #div2 gradually displayed. There are a large number of callback functions in jQuery

and there is a dedicated There is a method callbacks to manage

1

jQuery.Callbacks = function( options ) {...}

Copy after login

Finally, let me talk about the callbacks I have recently used in the project

The function of hybrid app is probably that I send a request to ios and ios returns the json to me. Data then I parse and insert the returned data into the web page

1

2

3

4

5

6

7

//首先我写一个javascript和ios通信callback函数(简化)getData(callback){

settimeOut(function(){callback(iso_return)},100);

}//然后我向ios发送一个请求function getSinersReuest(){window.location.href="vvmusic://....callback=getSinersData"}/*然后ios截获url中的callback执行getData(getSinersData)返回给我数据;我的getSinersData是我想把ios返回的json插入到页面显示8*/getSinersData(iso_return){

.........

}//当页面加载的时候调用window.onload=function(){

getSinersReuest();

}

Copy after login

The above is the detailed content of How to customize a callback function in jQuery. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1254
29
C# Tutorial
1228
24
Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

See all articles