Ok, this is a very simple question. I am actually 90% sure I know the answer, but the late hour is causing me to completely space it. I've searched it on SO and Google to no success.
How do I get return data from an event handler function?
I have several nests of event handlers, and need to get the result from the deepest out to the main output.
Like so (pseudocode):
mainFunction = function() {
attachToEvent( 'event1', function( e1 ) {
e.attachToEvent( 'event2', function( e2 ) {
return e2.status;
}
}
}
console.log( mainFunction() );
What is the proper pattern to get that return data( e2.status
) out to the console?
Again, I apologize for the simplicity of this question.
Thanks
You could either just log in the event handler or pass a callback into main function.
mainFunction = function(callback) {
arg.attachToEvent( 'event1', function( e1 ) {
e.attachToEvent( 'event2', function( e2 ) {
callback(e2.status);
}
}
}
mainFunction( function (e) { console.log(e); } );
This is not possible as console.log might had been executed before your event was fired.
See this example ( I am using a timer instead of an event )
var x = 1;
setTimeout( function(){
x = 2;
},1000)
console.log(x);// x = 1
By changing the scope of x
you can use console.log. Howerver as you can see in most cases this won't help
To your question:
mainFunction = function() {
var returnValue;
attachToEvent( 'event1', function( e1 ) {
e.attachToEvent( 'event2', function( e2 ) {
returnValue = e2.status;
}
}
return returnValue;
}
console.log( mainFunction() );
而不是return e2.status
你不能只写console.log(e2.status)
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.