2010-04-19 57 views
1

我有一个名为Location的类对象,它可以与Google一起使用,以对给定地址进行地址解析。 地理编码请求通过AJAX调用完成,并通过回调处理,一旦响应到达,该回调将启动类成员。Obj构造函数中的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] } 

我的问题是:有可能要等待从谷歌之前退出构造的反应如何?

我无法控制AJAX请求,因为它是通过谷歌API制作的。

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

谢谢!

+0

什么是这些属性获得者的好处?您给“this”的每个房产都是公开的。你可以很容易地删除getter并直接使用这些属性(只需创建不同的'Lat'和'Lng'属性而不是'coord'数组)。 – Tomalak 2010-04-19 17:29:32

回答

0

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

我不会推荐这种方法。当你创建一个JavaScript对象时,你通常不会期望它阻塞几百毫秒,直到谷歌响应。

此外,如果您尝试频繁请求(Source),Google将扼杀GClientGeocoder。客户可以在24小时内完成的请求数量也有上限。使用这种方法系统地处理这将会很复杂。如果您的JavaScript对象会随机失败,那么您可以轻松进入调试噩梦。

3

不,你不能(请阅读:不应该)等待。这就是为什么它首先被称为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()); 
});