Callbacks is a method introduced in jQuery 1.7, which is used to manage a group of callback functions with the same method parameters. In addition to adding, deleting, and clearing callbacks like arrays, Callbacks also provides several special modes. In different modes, the life cycle and execution order of callback functions are slightly different.
Generate callback column (Callbacks)
var callbacks = $.Callbacks(flags);
The parameter falgs is a string, used to indicate the mode of Callbacks. For example, in the "once stopOnFalse" mode, the callback will only be executed once at most. If the execution process If one of the callbacks returns false, the execution of the callback column will also be interrupted.
So where are the usage scenarios of jQuery.Callbacks?
In many cases it is necessary to control the sequential execution of a series of functions. Then generally a queue function is needed to handle this problem
Let's look at a piece of code
function Aaron(List, callback) { setTimeout(function() { var task = List.shift(); task(); //执行函数 if (task.length > 0) { //递归分解 setTimeout(arguments.callee, 1000) } else { callback() } }, 25) } Aaron([function(){ alert('a') },function(){ alert('b') }],function(){ alert('callback') }) 分别弹出 ‘a’ , ‘b’ ,’callback’
Pass in a set of function parameters, parse them recursively, and execute them one by one. In fact, you can use setTimeout to save the function The principle of executing only after adding to the end of the queue
*****But is it troublesome to write like this? *****
Let’s switch to the method provided by jQuery
var callbacks = $.Callbacks(); callbacks.add(function() { alert('a'); }) callbacks.add(function() { alert('b'); }) callbacks.fire(); //输出结果: 'a' 'b'
Is it much more convenient and the code is very clear, so it is a multi-purpose callback Function list objects provide a powerful way to manage callback function queues.
Also provides several convenient processing parameters
once: Ensure that this callback list is only executed (.fire()) once (like a deferred Deferred).
memory: keep the previous value, the latest value added to the back of this list will be executed immediately if any callback is called (like a Deferred).
unique: ensures that only one callback can be added at a time (so in the list There are no repeated callbacks).
stopOnFalse: When a callback returns false, interrupt the call
var callbacks = $.Callbacks('once'); callbacks.add(function() { alert('a'); }) callbacks.add(function() { alert('b'); }) callbacks.fire(); //输出结果: 'a' 'b' callbacks.fire(); //未执行
once’s function is to make the callback queue execute only once
Callbacks Mode
Default mode: The callbacks in the callback column can be executed multiple times by default, and the callback functions can be added repeatedly. But during execution, the newly added callback is not executed.
once: Each callback in the column is executed at most once. After the execution is completed, the callback function column is cleared.
memory: During the callback execution process, if a new callback is added, the new callback can also be executed.
Unique: The same callback cannot be added repeatedly.
stopOnFalse: If a callback returns false, subsequent callbacks will not be executed, even in memory mode.
var callbacks = $.Callbacks("once memory");
Callback execution order
The callbacks are saved in the array and then traversed through the for loop, so the callbacks in the column are executed in the order they are added, and the last one added is generally executed last.
// Fire the items on the list var foo = function( value ) { console.log( "foo:" + value ); }; // Add another function to the list var bar = function( value ){ console.log( "bar:" + value ); }; var callbacks = $.Callbacks(); callbacks.add( foo ); callbacks.add( bar); callbacks.fire("hello"); // output: foo: hello // output: bar: hello
The only exception is if the mark is memory and if fire() has been called before, then the new callback will be executed immediately using the parameters of the previous fire after it is added by add(). However, the callback called by fire() before add() will not be executed again immediately if fire() or fireWith() is not used.
Other key points
Calling Fire() or fireWith() of Callbacks in the callback function
There is a situation where it is called again in the callback Callbacks object's fire() or fireWith() method, what should I do in this case?
Jquery does this: call fire() or fireWith() in the callback, the Callbacks object just saves the parameters of fire() or fireWith(), and does not immediately execute the callback in the column. After all callbacks in callbacks have been executed, re-execute all callbacks in the Callbacks object with new parameters.
Note: If the mark is once, executing fire or fireWith() in the callback is invalid.
function fn1( value ){ console.log( value ); if (value == "bar!") return false; callbacks.fire("bar!"); } function fn2( value ){ console.log( "fn2 says: " + value); } var callbacks =$.Callbacks("stopOnFalse"); callbacks.add( fn1 ); callbacks.add( fn2 ); // Outputs: foo! // Outputs: fn2 says:foo! // Outputs: bar! callbacks.fire("foo!" );
After calling callbacks.disable(), callbacks can no longer be enabled
After calling disable(), the callback function list will be cleared. At this time, using fire or fireWith will not work. Any response. Therefore, Callbacks does not provide an enable method because all callbacks have been cleared and there is no need to enable them again.
callbacks.lock()
The callback column is locked, and calling callbacks.fire() or callbacks.fireWith() will be invalid.
If callbacks.lock() is called in a callback, there is one thing to note:
callbacks have a memory tag: there are no callbacks executed in the current fire() or fireWith() method. Execution will continue, but callbacks.fire() and callbacks.fireWith() in the callback will no longer work.
Callbacks have no memory tag: all callbacks are cleared, which means that subsequent callbacks will no longer be executed.
The strange thing is that Callbacks do not provide an unlock method. That is to say, once locked, Callbacks permanently lose the ability to call fire() or fireWith().
The above is the detailed content of What's the point of using Callbacks in jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


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

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

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