Search code examples
javascriptasynchronouscallbackreactjsw3c-geolocation

JavaScript - Adding a parameter to a success callback


Languages: Reactjs and vanilla JavaScript

The question is more of just a general JavaScript callback question but I'll add my React code to show how I ended up in this predicament.

Lets look,Tarantino style, at my confusing blunder:

I'm trying to send a callback as a parameter of a success callback

navigator.geolocation.getCurrentPosition(success(dataLoaded), error, options); 

but it didn't like because "pos" is suppose to be the "sole input parameter " for the success callback according to the docs.

Now lets rewind and figure out what got me into this mess:

I'm using a callback as a way of giving my React app the thumbs up that the asynchronous fetching is done and to render itself.

onDataLoaded: function() {
    this.setState({
        postsLoaded: true,
    });
  },
  componentDidMount: function(){
    WebAPIUtils.fetchComponentData(this.onDataLoaded);
  },
render: function() {
    if(!this.state.postsLoaded){
        return (<div className="Loading">Loading...</div>);
    }
    return (
      <div>
        //Components can be rendered now since their data is loaded. 
      </div>
    );
  }

Once the code below is successful I need to execute that callback:

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

function success(pos) {
  var crd = pos.coords;

  console.log('Your current position is:');
  console.log('Latitude : ' + crd.latitude);
  console.log('Longitude: ' + crd.longitude);
  console.log('More or less ' + crd.accuracy + ' meters.');
  //Here I want to execute my callback to render.
};

function error(err) {
  console.warn('ERROR(' + err.code + '): ' + err.message);
};

navigator.geolocation.getCurrentPosition(success, error, options);

But geolocation.getCurrentPosition has prescribed callbacks and so it seems there is no way of passing that callback as a parameter of the success callback

Is there a way to pass that callback as an extra parameter of the success callback? A callback being sent as a parameter of a callback seems weird but forming my original callback to also handle the location logic outside of the location module feels tacky too.


Solution

  • Use bind!

    navigator.geolocation.getCurrentPosition(
      success.bind(null, dataLoaded), 
      error, 
      options);
    
    //
    
    function success(dataLoaded, pos) {
      var crd = pos.coords;
    
      console.log('Your current position is:');
      console.log('Latitude : ' + crd.latitude);
      console.log('Longitude: ' + crd.longitude);
      console.log('More or less ' + crd.accuracy + ' meters.');
      dataLoaded();
    }
    

    This essentially creates a new version of a function where you can replace this and pre-fill arguments. So the callback being passed to getCurrentPosition is a single-parameter function that, when called, will become pos in your success function.