When doing Android development, often encounter the view of the event monitoring, although always used, but never think about its implementation principle. There are callback functions although often heard, but always feel dizzy, think of the head began to chaos. So write something today to get the idea right.
callback function
Here is the definition on Wikipedia:
In computer programming, a callback function , or a callback (Callback, which is called by call and back, is returned to the main function after the main function invocation), refers to a piece of executable code that passes through the function arguments to other code. This design allows the underlying code to invoke subroutines defined at the top level.
The definition of light may be obscure, the following is still back to the title, with the Java Interface Callback implementation button monitoring.
Java Interface callbacks
My code here basically imitates the Android button listening mode.
First define an interface, which defines the callback function onclick.
Public Interface Onclicklistener { void OnClick (Button b);}
Then we'll implement the Button class.
public class button { Onclicklistener listener; public void Setonclicklistener (Onclicklistener listener) { listener; public void printsomething (String msg) {System.out.println (msg); public void Click () {Listener.onclick ( this ); }}
Finally, it is called in the main function.
Public classCallbacktest { Public Static voidMain (string[] args) {button button=NewButton (); Button.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (Button b) {b.printsomething ("Button is clicked"); } }); System.out.println ("Start Analog Click"); System.out.println ("A real click should be called by the system."); Button.Click (); }}
The approximate process is that button.click () calls the callback function Onclicklistener.onclick, but the OnClick implementation is implemented in the anonymous inner class inside the Button.setonclicklistener. Language or expression is not very clear, so read more code.
The callback function in JS
By the way, the callback function in JS. Because the function of JS is also an object, it can be passed directly as a parameter, so it is very simple to implement.
// Analog Server return data var getinfo=function(id,callback) { var result= "<div>something Get By "+id+" </div> "; SetTimeout (function() { callback (result); },+); timer 1 seconds return data } // call getInfo (ID,function (Result) { // processing of returned result });
Java Interface callback Implementation button listener