地理位置成功回调-如何在此回调之外使用返回的对象? [英] Geolocation success callback - How do I work with the returned object outside this callback?

查看:52
本文介绍了地理位置成功回调-如何在此回调之外使用返回的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

网络上大多数简单的html5地理位置示例如下:

Most of the simple html5 geolocation examples on the web go something like:

if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(success, error);
} else {
    //no geolocation
}

function success(position) {
    //do things with the position object in here
}

function error (msg) {
    //log error codes etc here
}

我不想在成功回调中包含所有逻辑(有很多东西).将传递给成功的对象暴露给父范围的最佳方法是什么?通过以某种方式在成功中使用闭包?我不太明白.谢谢

I'd prefer not to have all my logic within the success callback (there's quite a bit). What's the best way of exposing the object passed to success to the parent scope? By using a closure within success somehow? I can't quite get it. Thanks

推荐答案

需要回调函数的原因是因为对getCurrentPosition的调用是异步的.因此,尽管您可以在父"范围(调用getCurrentPosition的范围)中将位置公开为变量,但这在调用getCurrentPosition的执行线程上没有用,因为这与成功的线程不同.功能.例如,这将不起作用:

The reason a callback function is required is because the call to getCurrentPosition is asynchronous. Therefore, while you can expose the position as a variable in scope of the "parent" (the scope in which getCurrentPosition is called), this isn't useful on the thread of execution that calls getCurrentPosition as this is different from that of the success function. For example, this won't work:

function parent(){
  var position;

  function success(p) {
    position = p;
  }

  function error (msg) {
    //log error codes etc here
  }

  navigator.geolocation.getCurrentPosition(success, error);
  var longitude = position.coords.longitude; // position is undefined here
}

但是,如果要将代码分解成较小的块,可以将位置存储在父级范围内的变量中(避免将其传递给他人),然后将多个函数链接在一起:

However, if you want to break down your code into smaller chunks, you can store the position in a variable within scope of the parent (avoids needing to pass it through) and then chain multiple functions together:

function parent(){
  var position;

  function success(p) {
    position = p;
    doSomethingWithPosition();
  }

  function error (msg) {
    //log error codes etc here
  }

  navigator.geolocation.getCurrentPosition(success, error);

  function doSomethingWithPosition(){
     var longitude = position.coords.longitude; // position is defined here
     doSomethingElseWithPosition();
  }

  function doSomethingElseWithPosition(){
     var latitude = position.coords.latitude; // position is defined here
  }

}

这篇关于地理位置成功回调-如何在此回调之外使用返回的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆