街景和主干变量范围

street view and backbone variable scoping

本文关键字:变量 范围      更新时间:2023-09-26

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

问题是在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);
        }
    },
});

你有几个选择。您可以使用_.bindAllprocessSVData绑定到相应的this

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

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

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

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

这将确保thisthis.processSVData作为sv.getPanoramzByLocation回调调用时的视图。您也可以使用 $.proxyFunction.bind 执行类似操作(如果您不必担心浏览器版本问题)。

或者你可以用通常的jQuery风格手动完成:

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

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