2013-04-09 24 views
0

onSuccess函數無限期運行,因爲會不斷詢問GPS接收器的座標。它包含一個函數createMap,只能執行一次。這是如何實現的?在函數外部做一個函數也不行,因爲它是作爲函數變量的參數值傳遞的。只運行一次禁止循環功能

watchID = navigator.geolocation.watchPosition(function(position) {onSuccess(position, arrMyLatLng);}, onError, options); 

function onSuccess(position, arrMyLatLng) 
{ 

var latitude , longitude ;  
latitude = position.coords.latitude ; 
longitude = position.coords.longitude; 
var myLatLng = new google.maps.LatLng(latitude, longitude); 

createMap(myLatLng, arrMyLatLng);// This feature will run for an indefinite number of times. It is only necessary once. 
map.panTo(myLatLng) ; 
} 
+0

到底是'createMap'什麼? – 2013-04-09 20:10:19

回答

1

您可以創建使用封閉私有狀態的功能:

onSuccess = (function() { 
    var created = false; 
    return function (position, arrMyLatLng) { 
     var latitude , longitude ;  
     latitude = position.coords.latitude ; 
     longitude = position.coords.longitude; 
     var myLatLng = new google.maps.LatLng(latitude, longitude); 
     if (!created) { 
      createMap(myLatLng, arrMyLatLng); 
      created = true; 
     } 
     map.panTo(myLatLng) ; 
    }; 
}()); 
+0

onSuccess constainly更新,並且「created」將始終爲false – user2244523 2013-04-09 20:15:42

+0

不,第一次onSuccess運行時,'created'將爲false,因此if控制結構運行,創建您的映射並將'created'設置爲true。從那裏開始,每次接下來的onSuccess調用,'created'都將成立。 – Bart 2013-04-09 20:19:31

+0

@ user2244523 - 不,這不是它的工作原理。當'onSuccess'被首次分配時,'created'將被設置爲'false'。請注意,'onSuccess'是外部函數返回的(匿名)函數。第一次'onSuccess'運行時,'created'將被設置爲'true',並且無法再次將其設置爲'false'。 – 2013-04-09 20:19:36

1

功能:

function runOnce() { 
    if (runOnce.done) { 
     return; 
    } else { 
     // do my code ... 

     runOnce.done = true; 
    } 
} 

因爲函數是對象在JavaScript中,你可以設置它的屬性。

0

假設createMap返回的地圖

var map = null; 

function onSuccess(position, arrMyLatLng) { 
    var latitude = position.coords.latitude ; 
    var longitude = position.coords.longitude; 
    var myLatLng = new google.maps.LatLng(latitude, longitude); 

    map = map || createMap(myLatLng, arrMyLatLng); 
    map.panTo(myLatLng); 
} 

createMap如果map評估爲 「假」(即是null),從而僅createMap運行一次將只運行。