2012-02-28 129 views
2

我正在研究使用Google Maps API的應用程序。我沒有使用JavaScript的經驗。我想要做的是以下幾點:JavaScript事件處理程序範圍

function SpeedMarker(position) { 
    this.speed = 50; 
    this.marker = new google.maps.Marker({ 
     position: position, 
     map: map, 
     icon: 'http://maps.google.com/mapfiles/markerA.png', 
     zIndex: Math.round(position.lat() * -100000) << 5 
    }); 
    google.maps.event.addListener(this.marker, 'click', this.ShowInfoWindow)   
} 

SpeedMarker.prototype.ShowInfoWindow = function() { 
    var contentString = 'stuff'; 
    infowindow = new google.maps.InfoWindow({ 
     content: contentString 
    }); 
    infowindow.open(map, this.marker); 
} 

問題是單擊事件發生在文檔對象中,並且this.marker在該上下文中不存在。

有沒有辦法處理我創建的SpeedMarker對象內的事件?

回答

5

變化

google.maps.event.addListener(this.marker, 'click', this.ShowInfoWindow); 

var self = this; 
google.maps.event.addListener(this.marker, 'click', function() { 
    self.ShowInfoWindow(); 
}); 

或使用Function.bind(警告:may require shim):

google.maps.event.addListener(this.marker, 'click', this.ShowInfoWindow.bind(this)); 
+0

OK,所以這可能是特定於Google地圖,但這裏是發生在什麼我運行上面的代碼(不是Function.bind): - 處理程序被調用,當我調用構造函數,沒有我點擊標記(如果我使用帶有警報的原始版本,則不會發生這種情況) -if我稍後嘗試運行此處理程序,我從Google地圖中收到錯誤消息:無法找到屬性' xx',(我猜,因爲我不再在地圖上下文,所以this.xx不存在) – user472875 2012-02-28 19:46:53

+0

我猜你錯過了匿名函數,並傳遞這樣的東西:'... addListener(this .marker,'click',self.ShowInfoWindow());'......這是不對的。 – 2012-02-28 19:57:25

+0

* Facepalm * - 我的錯誤:(現在完美的作品謝謝 – user472875 2012-02-28 20:00:16