开发者

Javascript assigning the return value of a Callback function to global variable

开发者 https://www.devze.com 2023-03-30 10:56 出处:网络
My question is about Javascript. I have a Callback function w开发者_开发知识库hich receives a Position object on a successful callback.

My question is about Javascript. I have a Callback function w开发者_开发知识库hich receives a Position object on a successful callback.

The problem is that when I try to set the properties of the Position object to a global variable at a successful callback it just does not let me do it and the global just remains undefined.

As a workaround to that instead of directly setting the object properties to global variables i'm trying to return it through the callback function but I couldn't find a way to set the return value of the callback function to a global variable.

Here's the simplified code.

var x;

navigator.geolocation.getCurrentPosition(onSuccess, onError);

//on Successful callback receives a Position Object
function onSuccess(position) {  
  var coords = position.coords;  
    x=coords;       // Setting directly to an object does not work x still remains undefined after succesful callback               
return coord; // Trying to set this to a global object 

}

// onError Callback receives a PositionError object
//
function onError(error) {
    alert('code: '    + error.code    + '\n' +
          'message: ' + error.message + '\n');
}


You can't return a value from the callback (in this case). That would mean that inside of getCurrentPosition, the return value from the callback has to be assigned somewhere.

Assigning it to a global variable works, but at the time you access that variable, it was not assigned the new value yet. E.g.

// x is assigned in `onSuccess`
var x;
navigator.geolocation.getCurrentPosition(onSuccess, onError);
alert(x); // will be undefined, the response is not processed yet

Think about it: getCurrentPosition is probably doing an Ajax request to get the position. Such a request takes (a) time (couple of milliseconds) and because of that (b) is asynchronous, which means that JavaScript does not wait until the response is received. Your code is way faster. onSuccess was not called yet when you alert x.

Only solution:

All the code that has to access the position as to be in or called from the callback.


As described by Felix King, you cannot return a value from a callback and in your global variable variant, the variable will not be set until after the AJAX request completes and calls the callback (hence its name !).

Using a global variable you can solve your problem if you have some sort of processing loop, you can add this code to that loop to do what is required whenever the coord changes.

  if (coord) // global variable has a new value
    // process it
     alert('code: '    + error.code    + '\n' +
          'message: ' + error.message + '\n');
    // then clear it
    coord = null;
  } 


have you tried setting it via the global window object?

//on Successful callback receives a Position Object
function onSuccess(position) {  
  var coords = position.coords;  
    window.x=coords;       // Setting directly to an object does not work x still remains undefined after succesful callback               
return coord; // Trying to set this to a global object 

}

also, since you return the coordinates from the success handler, is there not another way to get this value?


put a console.log(x); just after x=cords to check the value (works on Chrome and FF with FireBug)

do that also just after the call of OnSuccess.

Also don't forget that there is asynchronous code in JS (if you use AJAX to get the position), maybe you just don't receive the answer when you check the value of x


You can implement a helper method like flowing:

var LocationHelper = function() {};

LocationHelper.prototype.getLocation = function(callback) {

    navigator.geolocation.getCurrentPosition(onSuccess, onError);

    function onSuccess(pos) {
        callback({
            pos: pos
        });
    }

    function onError(message) {
        callback({
            message: message
        });
    }

  };
0

精彩评论

暂无评论...
验证码 换一张
取 消