Learning about Callbacks of jQuery source code
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 returnsfalse
once
: The callback function queue can only be triggered oncememory
: 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
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 arrayremove
: Delete the specified function from the callback queuehas
: Determine whether a function exists in the callback queueempty
: Clear the callback queuedisable
: Disable adding functions and trigger queues, clear the callback queue and the last incoming valuedisabled
: Determine whether the callback object is disabledlock
: Disablefire
, if memory is not empty, add will be invalid at the same timelocked
: Determine whetherlock
# is called ##fireWith
: Pass in
contextand parameters, trigger the queue
fire
: Pass in parameters Trigger object,
contextis the callback object
$.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.
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; }, ... }
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; }
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't re-fire // 当前执行函数范围false且options.stopOnFalse==true 直接跳至list尾 终止循环 firingIndex = list.length; memory = false; } } } // 没设置memory时不保留参数 // 设置了memory时 参数仍保留在其中 // Forget the data if we're done with it if ( !options.memory ) { memory = false; } firing = false; // Clean up if we'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 = ""; } } },
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

目录1:basename()2:copy()3:dirname()4:disk_free_space()5:disk_total_space()6:file_exists()7:file_get_contents()8:file_put_contents()9:filesize()10:filetype()11:glob()12:is_dir()13:is_writable()14:mkdir()15:move_uploaded_file()16:parse_ini_file()17:
