2010-04-19 33 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()); 
});