Home Web Front-end JS Tutorial Detailed implementation of jquery.Callbacks

Detailed implementation of jquery.Callbacks

Dec 03, 2016 pm 01:25 PM
jquery

Foreword

jQuery.Callbacks was added to jquery after version 1.7. It was extracted from the _Deferred object in version 1.6. It is mainly used to perform add, remove, fire, lock and other operations of function queues, and provides once , memory, unique, stopOnFalse four options for some special control.

Function introduction

jq’s Callbacks module mainly provides services for other modules. It is like a gentle little woman, paying silently behind the scenes. Deferred is like a giant, so prominent in jq, but internally, he is served by Callbacks.

Several states of Callbacks:

                                                                                                                      The callback function only executes once                                                                  OnFalse -- Terminate the callback list and continue execution when return false is encountered

Several simple methods of Callbacks that I implemented myself

                                                                            using using using using                 through out using off ’s ’ out’s ’ out’s out’s out’s out‐‐‐‐‐‐‐‐‐‐ Trigger callbacks, callback functions The list executes the functions in sequence


                                                                                                                                   . Do:

var cb = Callback('memory once') // 得到一个拥有记忆功能并只执行一次的回调模块
Copy after login

Since we need to get different instances based on a certain state, we can determine that we need an object to store the state

var callbackState = {}
Copy after login


We passed 'memory once' to the Callback function , how do we record these two states? Here, we implement it with a function written in jq, as follows:

var createCallbackState = function (options) {
 var states = options.split(' ')
 var obj = {}
 for (var i = 0; i < states.length; i++) {
  obj[states[i]] = true
 }
 return obj
 }
Copy after login


The above code changes 'memory once' into {memory: true, once: true}, if there is this object in the state cache object, it will be returned directly. If not, it will be created first and then returned.

Next, is the entire code of the Callback function. Let’s start with the code

var Callback = function (options) {
 
 var state = callbackState[options] //获取状态模式
 if (!state) {
  callbackState[options] = state = createCallbackState(options)
 }
 var list = [], // 回调函数列表
  memory,  // 存储是否为 记忆状态
  has = function (fn) {
  for (var i = 0; i < list.length; i++) {
   if (list[i] === fn) {
   return true
   }
  }
  return false
  },
  add = function () {
  var i = 0,
   args = arguments,
   len = args.length
  for (; i < len; i++) {
   if (state.unique && has(args[i])) { // 如果是unique状态下并回调列表已经拥有该函数,则不添加
   continue
   }
   list.push(args[i])
  }
  },
  fire = function (context, args) {
  var i = 0,
   len = list.length,
   item
  for (; i < len; i++) {
   item = list[i]
   if (item.apply(context,args) === false && state.stopOnFalse) { //如果函数运行返回false,并且是stopOnFalse状态,终止循环
   break;
   }
  }
  }
 
 return {
  add: function () {
  add.apply(null,arguments)
  // 如果memory模式并且已经拥有了memory信息,接着出发函数
  if (state.memory && memory) {
   fire(memory[0], memory[1])
   list = []
  }
  },
  fire: function (context, args) {
  // 如果memory模式,并且list是空,代表触发在添加前,保存memory信息
  if (state.memory && !list.length) {
   memory = [context, args]
   return
  }
  fire(context,args)
  if (state.once) {
   this.clear()
  }
  },
  has: function (fn) {
  return has(fn)
  },
  clear: function () {
  list = []
  }
 }
 
 }
Copy after login

After the Callback function is executed, it returns an object, and then the object contains several simple functions.

Let me introduce the implementation of this part.

First of all, like jq, I also defined the internal add, fire, and has methods. The main reason is the logical need. Once and memory state control are implemented in the method that returns the object. The internal add and fire methods are pure additions. and trigger functions.

Let’s look at the cb.add method first. The add method can receive multiple functions, so

add.apply(null,arguments)
Copy after login

Use the internal add to add the function

The next part of the function is to determine whether the callback module is memory Status, students who understand the Deferred module should know that this module is a Promise mode, subscribing to the callback function of the success or failure status, and then triggering it at a certain moment. This mode refers to the Callback in the memory state. This mode has a strange Where, if you publish successfully first, but the callback list is empty, then the program will not fail to publish, but wait for the successful callback function to be added. Once the callback function is added, it will be executed immediately.

is the following code

// 如果memory模式并且已经拥有了memory信息,立刻触发函数
 if (state.memory && memory) {
 fire(memory[0], memory[1])
 list = []
 }
Copy after login

Tip: 'If you publish successfully first, but the callback list is empty, then the program will not fail to publish, but will wait for the successful callback function to be added. Once the callback function is added, it will immediately Execute his understanding of the following code

var cb = Callback(&#39;memory&#39;) // 得到记忆功能的回调模块
 
cb.fire() // 触发回调队列
 
cb.add(fn) //添加回调函数,自动执行了!
 
function fn () {
 console.log(&#39;fn&#39;)
}
Copy after login

If it is in a non-memory state, the above code is invalid. It needs to be fired again to execute.

After the above, the fire function is easy to understand. fire can receive two parameters, function context and function parameter array.

Connected with the memory state code in add, the following code is the operation in the memory state during fire

// 如果memory模式,并且list是空,代表触发在添加前,保存memory信息
  if (state.memory && !list.length) {
   memory = [context, args]
   return
  }
Copy after login

If it is the memory state and the callback list is empty, save the function execution context and parameter array, etc. Execute immediately when add.

In addition to the above, the code is very simple and easy to understand. The Callback function ends here. It is a very simple function. The only thing that is difficult to understand is the memory status.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

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 use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

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

In-depth analysis: jQuery's advantages and disadvantages In-depth analysis: jQuery's advantages and disadvantages Feb 27, 2024 pm 05:18 PM

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

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

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

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: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

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? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

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

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

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

See all articles