【问题标题】:AJAX callback in Obj constructorObj 构造函数中的 AJAX 回调
【发布时间】:2010-04-19 17:08:06
【问题描述】:

我有一个名为 Location 的类对象,它与 Google 一起使用,以便对给定地址进行地理编码。 地理编码请求是通过 AJAX 调用发出的,并通过回调处理,一旦响应到达,该回调将启动类成员。

代码如下:

function Location(address) {
    this.geo = new GClientGeocoder();
    this.address = address;
    this.coord = [];

    var geoCallback = function(result) {
        this.coord[0] = result.Placemark[0].Point.coordinates[1];
        this.coord[1] = result.Placemark[0].Point.coordinates[0];
        window.alert("I am in geoCallback() lat: " + this.coord[0] + "; lon: " + this.coord[1]);
    }

    this.geo.getLocations(this.address, bind(this, geoCallback));                   
}
Location.prototype.getAddress = function() { return this.address; }
Location.prototype.getLat = function() { return this.coord[0] }
Location.prototype.getLng = function() { return this.coord[1] }

我的问题是:在退出构造函数之前可以等待 Google 的响应吗?

我无法控制 AJAX 请求,因为它是通过 Google API 发出的。

我想确保在创建 Location obj 后正确初始化 this.coord[]

谢谢!

【问题讨论】:

  • 这些属性获取器有什么用?您给this 的每个属性都是公开的。您可以轻松删除 getter 并直接使用属性(只需创建不同的 LatLng 属性,而不是 coord 数组)。

标签: javascript ajax constructor geocoding gdata-api


【解决方案1】:

不,您不能(阅读:不应该)等待。这就是为什么它首先被称为 AJAX(“Asynchronous Javascript ...”)。 ;)

您可以自己使用回调函数(前面的未经测试的代码)。

function Location(address, readyCallback) {
  this.geo = new GClientGeocoder();
  this.address = address;
  this.coord = [];
  this.onready = readyCallback;

  this.geo.getLocations(this.address, bind(this, function(result) {
    this.coord[0] = result.Placemark[0].Point.coordinates[1];
    this.coord[1] = result.Placemark[0].Point.coordinates[0];
    if (typeof this.onready == "function") this.onready.apply(this);
  }));
}
Location.prototype.getAddress = function() { return this.address; }
Location.prototype.getLat = function() { return this.coord[0] }
Location.prototype.getLng = function() { return this.coord[1] }

// ... later ...

var l = new Location("Googleplex, Mountain View", function() {
  alert(this.getLat());
});

【讨论】:

    【解决方案2】:

    是否可以等待响应 在退出之前从 Google 构造函数?

    我不推荐这种方法。创建 JavaScript 对象时,您通常不会期望它阻塞数百毫秒,直到 Google 做出响应。

    此外,如果您尝试执行频繁请求 (Source),Google 将限制 GClientGeocoder。客户在 24 小时内可以执行的请求数量也有上限。使用这种方法系统地处理这将是复杂的。如果您的 JavaScript 对象会随机失败,您很容易陷入调试噩梦。

    【讨论】:

      猜你喜欢
      • 2016-12-01
      • 2013-10-03
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2014-07-25
      • 2018-01-31
      • 1970-01-01
      相关资源
      最近更新 更多