[Javascript] zepto source code Callback analysis
The Callback module is used to manage callback functions and is also the basic part of the deferred delay object. Now let’s take a look at its source code.
Optional parameter:
Options: once: 是否最多执行一次, memory: 是否记住最近的上下文和参数 stopOnFalse: 当某个回调函数返回false时中断执行 unique: 相同得回调只被添加一次
This is an optional parameter, you can test it below:
var a = function (value) { console.log('a:' + value); }; var b = function (value) { console.log('b:' + value); }; var callbacks = $.Callbacks(); callbacks.add(a); callbacks.fire(['hello']); callbacks.add(b); callbacks.fire('中');
The following is his output result:
a: hello, a:中, b:中
You can see Yes, when we fire for the second time, function a will also be executed.
When adding parameters for experiments, first add memory
var callbacks = $.Callbacks({ memory: true }); callbacks.add(a); callbacks.fire('hello'); callbacks.add(b); 输出: a:hello, b:hello
Add memory parameters. Memory records the last time the callback function was triggered. Functions added thereafter will be executed immediately using this parameter. Looking at the use of once
var callbacks = $.Callbacks({ once: true }); callbacks.add(a); callbacks.fire('hello'); callbacks.fire('中'); 输出: a:hello
, we can see that although the fire method is executed twice, the result is only output once. The other two parameters are easy to understand, so you can try the details yourself.
$.Callbacks = function(options) { options = $.extend({}, options) var memory, fired, firing, firingStart, firingLength, firingIndex, list = [], stack = !options.once && [] }
Let’s take a look at the meaning of each parameter. memory will remember the last triggered context and parameters in memory mode. fired means whether the callback has been triggered. Firing means that the callback is being triggered. The firingStart callback task starts. Position, firingLength, the length of the callback task, firingIndex, the index of the current callback, and list represents the real callback queue. If it is not triggered once, it is used to cache the task parameters that are not executed during the triggering process.
fire = function(data) { memory = options.memory && data fired = true firingIndex = firingStart || 0 firingStart = 0 firingLength = list.length firing = true for ( ; list && firingIndex < firingLength ; ++firingIndex ) { if (list[firingIndex].apply(data[0], data[1]) === false && options.stopOnFalse) { memory = false break } } firing = false if (list) { if (stack) stack.length && fire(stack.shift()) else if (memory) list.length = 0 else Callbacks.disable() } }
The fire function is the only built-in function. Its function is to trigger the callback execution of the list. First, take a look at the parameters it passes in. It is not the same as the fire we call $.Callbacks externally. , data here is an array, data[0] represents the context, data[1] is the parameter of the method call. Then there is the initialization of each parameter. memory means that if options.memory is true, save the data, fired is true, if firingStart is 0, then firingIndex is 0, firingStart is set to 0, and the firing callback mark firing is true.
Then traverse the callback list and execute the callbacks one by one. The if judgment inside this means that if the callback function returns false and options.stopOnFalse is false, the memory cache will be cleared. After the traversal is completed, change the execution status to false. If the list exists and the stack also exists, take out the task parameters and call the fire function to execute. If memory exists, clear the list, otherwise perform callback execution.
Finally, this file returns Callbacks. Let’s take a look at its specific implementation:
Callbacks = { add: function () { if (list) { var start = list.length, add = function (args) { $.each(args, funciton(_, arg) { if (typeof arg === 'function') { if (!options.unique || !Callbacks.has(arg)) list.push(arg); } else if (arg && arg.length && typeof arg !== 'string') add(arg); }) } add(arguments) if (firing) firingLength = list.length; else if (memory) { firingStart = start; fire(memory) } } return this; } }
The main function of this function is to act like a list There is a push callback inside. First, determine whether the list exists. If it exists, start is assigned the length of the list, and an add method is added internally. The internal add method is mainly to add a callback to the list. If the parameter we pass in is an array, the add method is called again. Then call the add method and pass the arguments in. If the callback is in progress, the length of the callback task, firingLength, is the length of the current task list so that the callback function added subsequently can be executed. If memory exists, set the start to the first position in the newly added list, and then call fire.
Let’s take a look at how fireWith works:
fireWith: function(context, args) { if (list && (!fired || stack)) { args = args || []; args = [context, args.slice ? args.slice() : args]; if (firing) stack.push(args); else fire(args); } return this; }
The parameters passed in include context and parameter list. The condition for function execution is that the list exists and the callback is not executed or the stack exists, and the stack can be empty. First, reassign args. args[0] is the context and args[1] is the copied list. If the callback is in progress, add args to the stack, or just execute args.
Related articles:
Introduction to the Gesture module in the Zepto source code
A brief analysis of the Callback method in Javascript
The above is the detailed content of [Javascript] zepto source code Callback analysis. 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

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

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

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
