views:

20

answers:

3

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

+1  A: 

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() );
Ghommey
Ok, for sake of argument, let's say it's not. How would you do it?
Spot
The event is being emitted by third party code. I have no control over that.
Spot
A: 

Instead of return e2.status can't you just write console.log(e2.status)?

Skilldrick
Per that example, yes. In the actual code I am working with, no. The main function is called by an independent piece of code, and requires a return value from the call.
Spot
+1  A: 

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); } );
tarn
That's it! Thank you sir!
Spot
Your welcome :)
tarn