Home > Web Front-end > JS Tutorial > Detailed explanation of js callback function_javascript skills

Detailed explanation of js callback function_javascript skills

WBOY
Release: 2016-05-16 16:22:13
Original
971 people have browsed it

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.

Copy code The code is as follows:

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:

Copy code The code is as follows:

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:

Copy code The code is as follows:

           $("#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.

Copy code The code is as follows:



<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 매개변수가 할당되는 방식입니다. 이렇게 말하면 이 기능과 사용 방법을 이해할 수 있을 것입니다.

콜백은 다양한 프레임워크에서 널리 사용됩니다. 때로는 직접 작성할 때 실제 상황에 맞게 사용할 수도 있습니다.

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template