ビュー スコープ内でthis.mapを介してアクセスできる Google マップを含むビューがあります。世界ではすべてが順調です。
次に、ビュー内のイベントを介して地図の位置を更新したいと考えています。これを行うには、テキスト入力を取得し、google.maps.Geocoder.geocode() を使用してから、次の方法で位置を更新します。
setMapLocation: 関数 (場所) {
_.bind(this.setMapLocationCallback, this);
console.log(this);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': location}, this.setMapLocationCallback);
},
ここのconsole.log(this)はビューの範囲を示しており、this.mapに適切にアクセスできます。ここでコールバックを this に明示的にバインドしていることに注意してください。コールバックは次のとおりです。
setMapLocationCallback: function (results, status) {
console.log('this in the callback');
console.log(this);
if (status == google.maps.GeocoderStatus.OK) {
this.map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: this.map,
position: results[0].geometry.location
});
this.mapCanvas.css({visibility: 'visibile'});
} else {
this.mapCanvas.css({visibility: 'hidden'});
}
},
問題は、コールバックconsole.log(this)内で、ビュー オブジェクトの this スコープに明示的にバインドしたにもかかわらず、これが Window オブジェクトにスコープされていることを示していることです。
ページに複数のマップがあり、どのマップについて話しているかを区別する必要があるため、コールバックで this.map にアクセスする必要があります。
このコールバックを適切なスコープにバインドするにはどうすればよいですか? または、これを行うより良い方法はありますか?
私は backbonejs と underscorejs を使用していますが、これはかなり一般的な問題です。
前もって感謝します、デビッド