【问题标题】:JavaScript - Adding a parameter to a success callbackJavaScript - 向成功回调添加参数
【发布时间】:2015-12-27 10:54:33
【问题描述】:

语言:Reactjs 和原生 JavaScript

这个问题更像是一个一般的 JavaScript 回调问题,但我将添加我的 React 代码来说明我是如何陷入这种困境的。

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

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

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

但它不喜欢,因为根据docs,假定“pos”是成功回调的“唯一输入参数”。

现在让我们回顾一下是什么让我陷入了这个混乱:

我使用回调作为向我的 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 有 prescribed callbacks,所以似乎 无法将该回调作为成功回调的参数传递

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

【问题讨论】:

    标签: javascript asynchronous callback reactjs w3c-geolocation


    【解决方案1】:

    使用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 的回调是一个单参数函数,当被调用时,它将在您的success 函数中变为pos

    【讨论】:

    • 什么皮条客解决方案!让我试试看! :)
    猜你喜欢
    • 2015-06-05
    • 1970-01-01
    • 2013-12-18
    • 2012-10-25
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多