JavaScript - 将参数添加到成功回调

时间:2015-09-29 20:01:55

标签: javascript asynchronous callback reactjs w3c-geolocation

语言:Reactjs和vanilla JavaScript

问题更多的是一个一般的JavaScript回调问题,但我会添加我的React代码,以显示我是如何陷入这种困境的。

让我看看,塔伦蒂诺的风格,在我令人困惑的错误:

我尝试将回调作为成功回调的参数发送

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

但它并不喜欢因为" pos"被认为是唯一的输入参数"根据{{​​3}}成功回调。

现在让我们回顾并找出让我陷入困境的原因:

我使用回调作为向我的React应用程序竖起大拇指的方式,即完成异步提取并自我渲染。

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>
    );
  }

一旦下面的代码成功,我需要执行该回调:

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);

但是geolocation.getCurrentPosition有docs,所以似乎没有办法将该回调作为成功回调的参数传递

有没有办法将该回调作为成功回调的额外参数传递?作为回调参数发送的回调看起来很奇怪但是形成我原来的回调以处理位置模块外部的位置逻辑也感觉很俗气。

1 个答案:

答案 0 :(得分:3)

使用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和预填充参数。因此,传递给getCurrentPosition的回调是一个单参数函数,在调用时,将在pos函数中变为success

相关问题