Reputation: 8155
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
Upvotes: 1
Views: 2049
Reputation: 2182
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); } );
Upvotes: 3
Reputation: 38142
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() );
Upvotes: 1
Reputation: 70819
Instead of return e2.status
can't you just write console.log(e2.status)
?
Upvotes: 0