2013-09-24 34 views
1

定義Backbone模型時,'this'的範圍有問題。 在函數updateGeoLocation中,我調用一個匿名函數來處理標記位置和位置的更新。Backbone.js-模型方法中的'this'的範圍

問題是,當內部的匿名函數'this'是指窗口而不是模型。 我試圖把它添加到我的初始化功能,但它仍然沒有解決的問題:

_.bindAll(this , 'updateGeoLocation'); 

的代碼是:

var googleMapsModel = Backbone.Model.extend ({ 


    //Init map according to the window height 
    initialize: function() { 
     _.bindAll(this , 'updateGeoLocation'); 
     this.set('currentLocation', new google.maps.LatLng(-34.397, 150.644)); 
     $("#map-content").height(this.getRealContentHeight()); 
     var mapOptions = { 
      zoom: 15, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     }; 
     map = new google.maps.Map(document.getElementById("map-canvas"), 
      mapOptions); 
     this.updateGeoLocation(); 
    }, 
    //Update geo location and place marker on the map 
    updateGeoLocation: function() { 
     if (navigator.geolocation) { 
      navigator.geolocation.getCurrentPosition(function (position) { 
       lat = position.coords.latitude; 
       long = position.coords.longitude; 
       console.log (lat); 
       console.log((long)); 
       currentLocation = new google.maps.LatLng(lat,long); 
       map.setCenter(currentLocation); 
       //update marker 
       this.updateCurrentLocationMarker(currentLocation); 
      }) , function() { 
       alert("no Geo Location"); 
      }; 
     } 
    }, 
updateCurrentLocationMarker: function (markerLocation) { 
     myLocationMarker = new google.maps.Marker({ 
      position: markerLocation, 
      map: map 
     }); 
     this.model.set('currentLocationMarker', myLocationMarker); 
    }, 

任何幫助將appriciated

+0

當你從'initialize'或者你的代碼的其他部分調用它時,你失去了「this」? –

+0

在其他部分,問題在於updateGeoLocation裏面的匿名函數 –

+0

這很奇怪,因爲你在初始化,所以這是正確的模型實例,你調用'_.bindAll(this,'updateGeoLocation');'接着' this.updateGeoLocation();'。這應該工作! –

回答

1

更換你updateGeoLocation方法如下:

updateGeoLocation: function() { 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(_.bind(function (position) { 
      lat = position.coords.latitude; 
      long = position.coords.longitude; 
      console.log (lat); 
      console.log((long)); 
      currentLocation = new google.maps.LatLng(lat,long); 
      map.setCenter(currentLocation); 
      //update marker 
      this.updateCurrentLocationMarker(currentLocation); 
     }, this)) , function() { 
      alert("no Geo Location"); 
     }; 
    } 
}, 

這裏的關鍵是_.bin d,看看the doc

+0

工作原理,謝謝! –