0

我在以下呈现谷歌街景的主干视图中遇到问题。

问题是在 processSVData 函数中,this不是App.DetailStreetView. 当我console.log(this)进去时processSVData(),我得到了DOMWindow对象。因此,当尝试访问时,this.panorama我得到undefined

App.DetailStreetView = Backbone.View.extend({
    initialize: function() {
        this.latLng = new google.maps.LatLng(37.869085,-122.254775);
        this.panorama = new google.maps.StreetViewPanorama(this.el);
    },
    render: function() {
        var sv = new google.maps.StreetViewService();
        sv.getPanoramaByLocation(this.latLng, 50, this.processSVData);        
    },
    processSVData: function(data, status) {
        if (status == google.maps.StreetViewStatus.OK) {
            // calculate correct heading for POV
            //var heading = google.maps.geometry.spherical.computeHeading(data.location.latLng, this.latLng);
            this.panorama.setPano(data.location.pano);
            this.panorama.setPov({
                heading: 270,
                pitch:0,
                zoom:1, 
            });
            this.panorama.setVisible(true);
        }
    },
});
4

1 回答 1

1

你有几个选择。您可以使用_.bindAll绑定processSVData到适当的this

initialize: function() {
    _.bindAll(this, 'processSVData');
    //...
}

这将this始终使内部的视图processSVData

您也可以_.bind仅用于回调:

sv.getPanoramaByLocation(this.latLng, 50, _.bind(this.processSVData, this));

这将确保这是作为回调调用this时的视图。您也可以使用or做类似的事情(如果您不必担心浏览器版本问题)。this.processSVDatasv.getPanoramzByLocation$.proxyFunction.bind

或者您可以使用通常的 jQuery 样式手动完成:

var _this = this;
sv.getPanoramaByLocation(this.latLng, 50, function(data, status) {
    _this.processSVData(data, status);
});

第一种_.bindAll可能是 Backbone 中最常见的方法。

于 2012-06-16T02:47:35.347 回答