2012-02-28 132 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