3

ビュー スコープ内で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 を使用していますが、これはかなり一般的な問題です。

前もって感謝します、デビッド

4

1 に答える 1

5

変更してみてください

 geocoder.geocode({'address': location}, this.setMapLocationCallback);

を使用して、内部call()のスコープを変更できますthissetMapLocationCallback

 var _this = this;
 geocoder.geocode({'address': location}, function(result, status) {
     _this.setMapLocationCallback.call(_this, result, status);
 });

call() 関数に関する MDN ドキュメント

于 2012-05-09T12:56:11.253 に答える