Basic implementation and usage of jQuery Callback
In js development, since there is no multi-threading, we often encounter the concept of callback. For example, registering a callback function in the ready function, registering event processing of elements, etc. In more complex scenarios, when an event occurs, multiple callback methods may need to be executed at the same time. The implementation that can be directly considered is to implement a queue and add all functions that require callbacks when the event is triggered to this queue for storage. When the event is triggered, the saved functions are sequentially retrieved from this queue and executed.
Overview
$(document).ready() abbreviation.
Allows you to bind a function to be executed after the DOM document is loaded. This function works the same as $(document).ready(), except that when using this function, you need to wrap all the $() operators in the page that need to be executed when the DOM is loaded. Technically, this function is chainable - but not many cases actually link in this way. You can use any number of $(document).ready events on a page. See ready(Function) for more information on the ready event.
Parameters
callbackFunctionV1.0
The function to be executed when the DOM is loaded
can be implemented simply as follows.
First, implement a class function to represent this callback class. In javascript, use an array to represent this queue.
function Callbacks() { this.list = []; }
Then, implement the methods in the class through the prototype. The added and deleted functions are stored in the array. When firing, you can provide parameters, which will be passed to each callback function.
Callbacks.prototype = { add: function(fn) { this.list.push(fn); }, remove: function(fn){ var position = this.list.indexOf(fn); if( position >=0){ this.list.splice(position, 1); } }, fire: function(args){ for(var i=0; i<this.list.length; i++){ var fn = this.list[i]; fn(args); } } };
The test code is as follows:
function fn1(args){ console.log("fn1: " + args); } function fn2(args){ console.log("fn2: " + args); } var callbacks = new Callbacks(); callbacks.add(fn1); callbacks.fire("Alice"); callbacks.add(fn2); callbacks.fire("Tom"); callbacks.remove(fn1); callbacks.fire("Grace");
Or, do not use prototypes and implement them directly through closures.
function Callbacks() { var list = []; return { add: function(fn) { list.push(fn); }, remove: function(fn){ var position = list.indexOf(fn); if( position >=0){ list.splice(position, 1); } }, fire: function(args) { for(var i=0; i<list.length; i++){ var fn = list[i]; fn(args); } } }; }
In this case, the sample code also needs to be adjusted. We can just use the Callbacks function directly.
function fn1(args){ console.log("fn1: " + args); } function fn2(args){ console.log("fn2: " + args); } var callbacks = Callbacks(); callbacks.add(fn1); callbacks.fire("Alice"); callbacks.add(fn2); callbacks.fire("Tom"); callbacks.remove(fn1); callbacks.fire("Grace");
Let’s continue using the second method.
For more complex scenarios, we need to fire only once. Even if fire is called in the future, it will no longer take effect.
For example, it may be in this form when creating an object. The use of once here means that it can only fire once.
var callbacks = Callbacks("once");
Then, our code also needs to be adjusted. In fact, it is very simple. If once is set, then after fire, just kill the original queue directly.
function Callbacks(options) { var once = options === "once"; var list = []; return { add: function(fn) { if(list){ list.push(fn); } }, remove: function(fn){ if(list){ var position = list.indexOf(fn); if( position >=0){ list.splice(position, 1); } } }, fire: function(args) { if(list) { for(var i=0; i<list.length; i++){ var fn = list[i]; fn(args); } } if( once ){ list = undefined; } } }; }
jQuery not only provides once method, but provides four types of different methods:
once: can only be triggered once.
memory: When the queue has been triggered, the function added will be called directly without triggering again.
unique: Guarantee the uniqueness of the function
stopOnFalse: As long as one callback returns false, subsequent calls will be interrupted.
These four methods can be combined, just use spaces to separate them into the constructor, such as $.Callbacks("once memory unique");
The official documentation provides some methods for use Example.
callbacks.add(fn1, [fn2, fn3,...])//Add one/multiple callbacks
callbacks.remove(fn1, [fn2, fn3,...])/ /Remove one/multiple callbacks
callbacks.fire(args)//Trigger callback, pass args to fn1/fn2/fn3...
callbacks.fireWith(context, args)//Specify context context and then Trigger callback
callbacks.lock()//Lock the current triggering status of the queue
callbacks.disable()//Disable the manager, that is, all fires will not take effect
The above is the detailed content of Basic implementation and usage of jQuery Callback. For more information, please follow other related articles on the PHP Chinese website!

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.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.


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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft