Home > Web Front-end > JS Tutorial > body text

Learning about Callbacks of jQuery source code

不言
Release: 2018-07-09 10:57:34
Original
1341 people have browsed it

This article mainly introduces the learning of Callbacks of jQuery source code. It has a certain reference value. Now I share it with everyone. Friends in need can refer to it

JQuery source code learning of Callbacks

jQuery's ajax and deferred implement asynchronously through callbacks, and the core of their implementation is Callbacks.

Usage method

To use it, you must first create a new instance object. When creating, you can pass in the parameter flags to indicate restrictions on callback objects. The optional values ​​are as follows.

  • stopOnFalse: Stop triggering when the function in the callback function queue returns false

  • once: The callback function queue can only be triggered once

  • memory: Record the value passed in the last trigger queue, and add it to the queue The function takes the record value as argument and executes immediately.

  • unique: The functions in the function queue are all unique

var cb = $.Callbacks('memory');
cb.add(function(val){
    console.log('1: ' + val)
})
cb.fire('callback')
cb.add(function(val){
    console.log('2: ' + val)
})
// console输出
1: callback
2: callback
Copy after login

Callbacks provided A series of instance methods to manipulate the queue and view the status of the callback object.

  • add: Add a function to the callback queue, which can be a function or a function array

  • remove: Delete the specified function from the callback queue

  • has: Determine whether a function exists in the callback queue

  • empty: Clear the callback queue

  • disable: Disable adding functions and trigger queues, clear the callback queue and the last incoming value

  • disabled: Determine whether the callback object is disabled

  • lock: Disablefire , if memory is not empty, add will be invalid at the same time

  • locked: Determine whether lock

  • # is called
  • ##fireWith: Pass in context and parameters, trigger the queue

  • fire: Pass in parameters Trigger object, context is the callback object

Source code analysis

$.Callback()The method defines multiple Local variables and methods are used to record the status of the callback object and function queue, etc., and return self. The above callback object methods are implemented in self, and the user can only pass self Provides methods to change the callback object. The advantage of this is to ensure that there is no other way to modify the status and queue of the callback object except self.

Among them,

firingIndex is the index of the current triggering function in the queue, list is the callback function queue, memory records the parameters of the last trigger , used when memory is passed in when the callback object is instantiated, queue saves the context and parameters passed in when each callback is executed. self.fire(args) is actually self.fireWith(this, args), self.fireWith internally calls Callbacks Defined local function fire.

    ...
    // 以下变量和函数 外部无法修改,只能通过self暴露的方法去修改和访问
    var // Flag to know if list is currently firing
        firing,

        // Last fire value for non-forgettable lists
        // 保存上一次触发callback的参数,调用add之后并用该参数触发
        memory,

        // Flag to know if list was already fired
        fired,

        // Flag to prevent firing
        // locked==true fire无效 若memory非空则同时add无效
        locked,

        // Actual callback list
        // callback函数数组
        list = [],

        // Queue of execution data for repeatable lists
        // 保存各个callback执行时的context和传入的参数
        queue = [],

        // Index of currently firing callback (modified by add/remove as needed)
        // 当前正触发callback的索引
        firingIndex = -1,

        // Fire callbacks
        fire = function() {
            ...
        },
        
        // Actual Callbacks object
        self = {
            // Add a callback or a collection of callbacks to the list
            add: function() {
                ...
            },
            ...
            // Call all callbacks with the given context and arguments
            fireWith: function( context, args ) {
                if ( !locked ) {
                    args = args || [];
                    args = [ context, args.slice ? args.slice() : args ]; // :前为args是数组,:后是string
                    queue.push( args );
                    if ( !firing ) {
                        fire();
                    }
                }
                return this;
            },

            // Call all the callbacks with the given arguments
            fire: function() {
                self.fireWith( this, arguments );
                return this;
            },
            ...
        }
Copy after login

Add the function to the callback queue through

self.add, the code is as follows. First determine whether memory is not being triggered. If so, move fireIndex to the end of the callback queue and save memory. Then use the immediate execution function expression to implement the add function, traverse the incoming parameters in this function, and determine whether to add it to the queue after performing type judgment. If the callback object has the unique flag, you must also judge the Whether the function already exists in the queue. If the callback object has the memory flag, fire will be triggered after the addition is completed to execute the newly added function. The

            add: function() {
                if ( list ) {

                    // If we have memory from a past run, we should fire after adding
                    // 如果memory非空且非正在触发,在queue中保存memory的值,说明add后要执行fire
                    // 将firingIndex移至list末尾 下一次fire从新add进来的函数开始
                    if ( memory && !firing ) {
                        firingIndex = list.length - 1;
                        queue.push( memory );
                    }

                    ( function add( args ) {
                        jQuery.each( args, function( _, arg ) {
                            // 传参方式为add(fn)或add(fn1,fn2)
                            if ( jQuery.isFunction( arg ) ) {
                                /**
                                 * options.unique==false
                                 * 或
                                 * options.unique==true&&self中没有arg
                                 */
                                if ( !options.unique || !self.has( arg ) ) {
                                    list.push( arg );
                                }
                            } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) {
                                // 传参方式为add([fn...]) 递归
                                // Inspect recursively
                                add( arg );
                            }
                        } );
                    } )( arguments ); //arguments为参数数组 所以add的第一步是each遍历

                    //添加到list后若memory真则fire,此时firingIndex为回调队列的最后一个函数
                    if ( memory && !firing ) {
                        fire();
                    }
                }
                return this;
            }
Copy after login

fire and fireWith methods actually call the local function fire, and the code is as follows. When triggered, fired and firing need to be updated to indicate that it has been triggered and is being triggered. Execute the functions in the queue through a for loop. After ending the loop, update firingIndex to -1, indicating that the next firing starts from the first function in the queue. Traverse the queue updated in fireWith, queue is the array that holds the array, and the first element of each array is context ,The second element is the parameter array. When executing the function, check whether false is returned and the callback object has the stopOnFalse flag. If so, stop triggering.

// Fire callbacks
        fire = function() {

            // Enforce single-firing
            // 执行单次触发
            locked = locked || options.once;

            // Execute callbacks for all pending executions,
            // respecting firingIndex overrides and runtime changes
            // 标记已触发和正在触发
            fired = firing = true;
            // 循环调用list中的回调函数
            // 循环结束之后 firingIndex赋-1 下一次fire从list的第一个开始 除非firingIndex被修改过
            // 若设置了memory,add的时候会修改firingIndex并调用fire
            // queue在fireWith函数内被更新,保存了触发函数的context和参数
            for ( ; queue.length; firingIndex = -1 ) {
                memory = queue.shift();
                while ( ++firingIndex < list.length ) { 

                    // Run callback and check for early termination
                    // memory[0]是content memory[1]是参数
                    if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
                        options.stopOnFalse ) {
                        
                        // Jump to end and forget the data so .add doesn&#39;t re-fire
                        // 当前执行函数范围false且options.stopOnFalse==true 直接跳至list尾 终止循环
                        firingIndex = list.length;
                        memory = false;
                    }
                }
            }

            // 没设置memory时不保留参数
            // 设置了memory时 参数仍保留在其中
            // Forget the data if we&#39;re done with it
            if ( !options.memory ) {
                memory = false;
            }

            firing = false;

            // Clean up if we&#39;re done firing for good
            if ( locked ) {

                // Keep an empty list if we have data for future add calls
                if ( memory ) {
                    list = [];

                // Otherwise, this object is spent
                } else {
                    list = "";
                }
            }
        },
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Introduction to js asynchronous for loop

The above is the detailed content of Learning about Callbacks of jQuery source code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!