Notes on callback functions in js

  • 2020-03-30 03:37:24
  • OfStack

What is the callback function before learning how to use and function of js callback function, the following article put me in the study of callback function example for you to introduce it, there is need to understand the students do not guard against reference.

Principle of callback function:

I'm leaving now, and I'll let you know when I get there."
This is an asynchronous process, where "I'm off" (the function executes), "you" can do anything, "here" (the function completes), "notify you" (the callback) goes on

example

1. Basic methods


<script language="javascript" type="text/javascript">
function doSomething(callback) {
//  ...  
// Call the callback
callback('stuff', 'goes', 'here');
} 
function foo(a, b, c) {
// I'm the callback
alert(a + " " + b + " " + c);
} 
doSomething(foo); 
</script>

Or in the form of anonymous functions


<script language="javascript" type="text/javascript">
 function dosomething(damsg, callback){
  alert(damsg);
  if(typeof callback == "function") 
  callback();
 } 
dosomething(" The callback function ", function(){
  alert(" and  jQuery  the  callbacks  forms !");
 }); 
</script>

 
2. Advanced methods
 
Use the javascript call method


<script language="javascript" type="text/javascript">
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback) {
// Call our callback, but using our own instance as the context
callback.call(this);
}
 
function foo() {
alert(this.name);
}
 
var t = new Thing('Joe');
t.doSomething(foo); // Alerts "Joe" via `foo`
</script>

 
The parameter


<script language="javascript" type="text/javascript"> 
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback, salutation) {
// Call our callback, but using our own instance as the context
callback.call(this, salutation);
} 
function foo(salutation) {
alert(salutation + " " + this.name);
} 
var t = new Thing('Joe');
t.doSomething(foo, 'Hi'); // Alerts "Hi Joe" via `foo`
</script>

Pass the parameter apply using javascript


<script language="javascript" type="text/javascript">
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback) {
// Call our callback, but using our own instance as the context
callback.apply(this, ['Hi', 3, 2, 1]);
} 
function foo(salutation, three, two, one) {
alert(salutation + " " + this.name + "  �  " + three + " " + two + " " + one);
} 
var t = new Thing('Joe');
t.doSomething(foo); // Alerts "Hi Joe  �  3 2 1" via `foo`
</script>

example
// if the data source provided is an integer, is the score of a student, when num< =0, processed by the bottom layer, when n> At 0, it is handled by the higher level.

// copy the following function and save it as 1.js


function f(num,callback){
 if(num<0) { 
 alert(" Call low-level function processing !");
 alert(" The score cannot be negative , Input error !"); 
 }else if(num==0){
  alert(" Call low-level function processing !");
 alert(" The student may not have taken the exam! ");
 }else{
 alert(" Call the high-level function handle !");
 callback();
 }
}

// save the following test.html file in the same directory with 1.js:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<script src="1.js" type="text/javascript"></script>
<title> Headless document </title>
<script type="text/javascript">
 function test(){
  var p=document.getElementById("pp");
 pp.innerText="";
  var num=document.getElementById("score").value;
 f(num,function(){ //Anonymous high-level handler
 if(num<60) alert(" Did not pass the exam! ");
 else if(num<=90) alert(" The student got good grades! ");
 else alert(" The student has an excellent record !"); })
 pp.innerText="by since1978 qq558064!"
 }
</script>
</head>

<body>
<p>
 Example callback function : When students get grades score<=0 Divided by time, by the bottom processing; when score>0 , by the high-level processing. 
</p>
 Please enter the student's grade <input type="text" id="score"> 
<input type="button" onClick="test()" value="  Look at the results ">
<p id="pp"></p>
</body>
</html>

Here's what others have to add:

Callback mode in javascript:

Like:


function writeCode(callback){ 
   //Perform something,
   callback(); 
   //... 
  } 
 
  function intrduceBugs(){ 
   //. Introduction of holes
  } 
 
writeCode(intrduceBugs); 

              We pass the application of the function to writeCode(), and let the writeCode execute it at the appropriate time.

Let's take a look at a bad example (to be refactored later) :


//Simulate the search for dom nodes in the page, and uniformly return the nodes found in the array
  //This function is only used for lookup without any logical processing of the dom node
  var findNodes = function(){ 
   var i = 100000;//Lots of cycles,
   var nodes = [];//Use to store the dom node found
   var found; 
   while(i){ 
    i -=1; 
    nodes.push(found); 
   } 
   return nodes; 
  } 
 
  //Hide all the dom nodes found in the search
  var hide = function(nodes){ 
   var i = 0, 
    max = nodes.length; 
   for(;i<max;i++){ 
//FindNodes is followed by parentheses for immediate execution, first findNodes() and then hide()<Hide (findNodes ()); Execute function};
nodes[i].style.display="none"
}

 The above method is inefficient, thought hide() It has to be traversed again findNodes() The returned array node, how to avoid this redundant loop.  
   We can't go straight in findNodes By hiding the queried node (so that the retrieval can modify the logic coupling), it is no longer a generic function.  
   The solution is to use the callback pattern, which passes the node hiding logic to the callback function findNodes() And entrust it with execution 

//Refactor findNodes to accept a callback function
   var findNodes = fucntion(callback){ 
    var i = 100000, 
     nodes = [], 
     found; 
    //Checks whether the callback function is available for invocation
    if(typeof callback !== 'function'){ 
     callback = false; 
    } 
    while(i){ 
     i -= 1; 
     if(callback){ 
      callback(found); 
     } 
     nodes.push(found); 
    } 
    return nodes; 
   } 
 
   //The callback function
   var hide = function(node){ 
    node.style.display = 'none '; 
   } 
   //Find subsequent nodes and hide them for subsequent execution
 findNodes(hide);// To perform first findNodes Then perform hide Of course, the callback function can also be created when calling the main function: findNodes(function(node){node.style.display = 'none';});

Related articles: