0

I have script1 and script2. Here is some code from script1:

var pos;

function foo(param){pos = param;}

bar(foo);

Now in script2:

function bar(callback){
    //prints 'function'
    console.log(typeof callback);

    navigator.geolocation.getCurrentPosition(
        success,
        fail
    );
}

function success(position, callback){
    //prints 'undefined'
    console.log(typeof callback);
    var pos= {
        lat: position.coords.latitude, 
        long: position.coords.longitude
    };
    callback(pos);
}

How do I correctly pass foo as a callback function to bar, and chain it to navigator.geolocation.getCurrentPosition? How can I correctly get pos back to script1? Why can't I just return the values instead??

3

2 Answers 2

3

You need to re-pass the callback to the success function

function bar(callback){
    //prints 'function'
    console.log(typeof callback);

    navigator.geolocation.getCurrentPosition(
        function(pos){
            // repass callback to success method
            success(pos, callback);
        },
        fail
    );
}
Sign up to request clarification or add additional context in comments.

2 Comments

this works, but as someone from a Java background, i just don't understand - even though i know that functions are objects in javascript
getCurrentPostion(success, fail) passes two function pointers to invoke async and those methods don't know anything about the scope where it is invoked - same applies to Java. in parameters are private scope - just like Java
0
var pos;

function foo(param){pos=param; console.log(param);}

bar(foo);

function bar(callback){
    //prints 'function'
    //console.log(callback);

    navigator.geolocation.getCurrentPosition(
         success.bind(null, callback), 
        fail
    );

}

function success(callback, position){
    //prints 'function'

    var pos= {
        lat: position.coords.latitude, 
        long: position.coords.longitude
    };

   callback(pos);
}

function fail(){
  console.log('failed');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.