2012-06-16 25 views
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); 
     } 
    }, 
}); 

回答

1

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

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

这将使this始终内部processSVData的看法。

您也可以使用_.bind只是回调:

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

这将确保this是当this.processSVData被称为一个sv.getPanoramzByLocation回调的观点。您可以使用$.proxyFunction.bind(如果您不必担心浏览器版本问题)做类似的事情。

或者你可以用手在平时的jQuery的风格做到这一点:

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

第一,_.bindAll,很可能是在骨干网中最常用的方法。

+0

最好的解决方案,因为你已经在页面上有下划线。尽可能使用本地绑定。 – adrian

+0

@ amchang87:下划线的'_.bindAll'建立在'_.bind'上,并且AFAIK,'_.bind'使用本地的'Function.bind'(如果可用)。 –