Detailed explanation of js callback function_javascript skills
Making native Apps and Web Apps is now the mainstream, which means that various browser-based web app frameworks are becoming more and more popular, and those doing js are becoming more and more promising. I also decided to gradually move from back-end development to front-end development and mobile development. Without further ado, let’s get to the point of things related to “js callback functions”.
Speaking of callback functions, although many people know what they mean, they still have little understanding. As for how to use it, I'm still a bit confused. Some relevant information on the Internet does not explain in detail what is going on, and the explanation is relatively one-sided. Below I am just talking about my personal understanding, don’t criticize the big guys. Let's take a look at a rough definition: "Function a has a parameter, which is a function b. When function a is executed, function b is executed. Then this process is called callback." This sentence means that function b starts with Function a is passed in as a parameter and executed. The order is to execute a first, and then execute parameter b. b is the so-called callback function. Let's look at the following example first.
function a(callback){
alert('a');
callback.call(this);//or callback(), callback.apply(this), depending on personal preference
}
function b(){
alert('b');
}
//Call
a(b);
This result is that 'a' pops up first, and then 'b' pops up. I guess someone will ask, "What's the point of writing such code? It doesn't seem to have much effect!"
Yes, actually I also think it is meaningless to write like this, "If you call a function, just call it directly in the function." I just wrote a small example for everyone to gain a preliminary understanding. In the actual process of writing code, such parameters are rarely used, because in most scenarios, we have to pass parameters. Here’s one with parameters:
function c(callback){
alert('c');
callback.call(this,'d');
}
//Call
c(function(e){
alert(e);
});
Does this call look familiar? Here the e parameter is assigned the value 'd'. We simply assign it as a character. In fact, it can also be assigned as an object. Is there an e parameter in Jquery? Let’s talk about it below
How the e parameter in Jquery is assigned by callback.
I think everyone is familiar with the Jquery framework. It has been out for a long time and is used during development. It is relatively simple. It is very convenient to search the API online and it is quick to get started. In the Jquery framework, we sometimes need to obtain some parameters in the event. For example, I want to obtain the coordinates of the current click and the clicked element object. This requirement is easy to handle in Jquery:
$("#id").bind('click',function(e){
//e.pageX, e.pageY, e.target... Various data
});
It is quite convenient to use. In fact, the assignment of the e parameter is also implemented through the callback function. This parameter is given an object value using the callback parameter. Friends who have carefully studied the JJquery source code should have discovered this.
The same principle applies to the data parameter in Ajax $.get('',{},function(data){}).
Let’s take a look at how the callback function is applied in the Jquery event object.
For the sake of convenience, I simply wrote some implementations related to $. I have written about "Small Talk about Jquery" before, which has a method that is closer to the framework implementation. I will just write a simple selector below.
<script><br /> var _$=function (id)<br /> { <br /> this.element= document.getElementById(id); <br /> }<br /> _$.prototype={<br /> bind:function(evt,callback)<br /> {<br /> var that=this;<br /> if(document.addEventListener)<br /> {<br /> this.element.addEventListener(evt, function(e){<br /> callback.call(this,that.standadize(e));<br /> } ,false);<br /> }<br /> else if(document.attachEvent)<br /> {<br /> this.element.attachEvent('on' evt,function(e){<br /> callback.call(this,that.standadize(e));<br /> });<br /> }<br /> else<br /> this.element['on' evt]=function(e){<br /> callback.call(this,that.standadize(e));<br /> };<br /> },<br /> standadize:function(e){<br /> var evt=e||window.event;<br /> var pageX,pageY,layerX,layerY;<br /> //pageX 横坐标 pageY纵坐标 layerX点击处位于元素的横坐标 layerY点击处位于元素的纵坐标<br /> if(evt.pageX)<br /> {<br /> pageX=evt.pageX;<br /> pageY=evt.pageY;<br /> }<br /> else<br /> {<br /> pageX=document.body.scrollLeft evt.clientX-document.body.clientLeft;<br /> pageY=document.body.scrollTop evt.clientY-document.body.clientLTop;<br /> }<br /> if(evt.layerX)<br /> {<br /> layerX=evt.layerX;<br /> layerY=evt.layerY;<br /> }<br /> else<br /> {<br /> layerX=evt.offsetX;<br /> layerXY=evt.offsetY;<br /> }<br /> return {<br /> pageX:pageX,<br /> pageY:pageY,<br /> layerX:layerX,<br /> layerY:layerY<br /> }<br /> }<br /> }<br /> window.$=function(id)<br /> {<br /> return new _$(id);<br /> }<br /> $('container').bind('click',function(e){<br /> alert(e.pageX);<br /> });<br /> $('container1').bind('click',function(e){<br /> alert(e.pageX);<br /> });<br /> </script>
这段代码我们主要看standadize函数的实现,兼容性的代码,就不多说了,返回的是一个对象
return {
pageX:pageX,
pageY:pageY,
layerX:layerX,
layerY:layerY
}
然后再看bind函数里面的代码 callback.call(this,that.standadize(e)),这段代码其实就是给e参数赋值了,是用callback回调实现的。
callback 函数被调用的时候传入的是匿名函数
function(e){
}
而callback.call(this,that.standadize(e))相当于是执行了这么一段代码
(함수(e){
})(표준화(e))
이는 Jquery가 콜백 함수를 사용하는 전형적인 장소이기도 합니다. 이것이 e 매개변수가 할당되는 방식입니다. 이렇게 말하면 이 기능과 사용 방법을 이해할 수 있을 것입니다.
콜백은 다양한 프레임워크에서 널리 사용됩니다. 때로는 직접 작성할 때 실제 상황에 맞게 사용할 수도 있습니다.

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.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...


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

Dreamweaver Mac version
Visual web development tools

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

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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