2013-11-05 2 views
0

다른 색상으로 렌더링하려고하는 방향 설정이 있습니다. 구글의 지시를 요청하지만 상태를 저장하는 방법을 모르므로 라우팅 결과가 반환되면 각각을 적절한 색으로 렌더링 할 수 있습니다.상태를 자바 스크립트의 하위 함수로 전달 하시겠습니까?

그래서, 예를 들어, 나는이 목적을 가지고 : 나는 for 루프에서 (예를 들어, 인덱스 상태를 연결할 수있는 방법

directionsService = new google.maps.DirectionsService(); 
for(var i = 0; i < routes.length; i++){ 
    var dir_request = { 
     origin : new google.maps.LatLng(routes[i]['start_lat'], routes[i]['stop_lng']), 
     destination : new google.maps.LatLng(routes[i]['end_lat'], routes[i]['end_lng']), 
     travelMode : google.maps.TravelMode.WALKING 
    }; 
    directionsService.route(dir_request, function(result, status) { 
     if(status == google.maps.DirectionsStatus.OK){ 
      // render with custom logic depending on which route this is here 
     } 
    }) 
} 

: 여기

{routes: [{start_lat : 0.0, start_lng : 0.0, end_lat : 1.0, end_lng : 1.0, color : "#ff0000"}, 
      {start_lat : 1.0, start_lng : 1.0, end_lat : 2.0, end_lng : 2.0, color : "#00ff00"}]} 

내 기능입니다)를 각 요청에 추가하여 결과 처리 함수에서 액세스 할 수 있도록 하시겠습니까?

+0

이 호출 폐쇄, 나는 – Markasoftware

답변

1

이렇게하려면 closurescoped variables을 사용해야합니다. 경로 콜백 함수에서 i을 사용하려고하면 클로저 (closure)라는 개념을 사용하고 있습니다. 여기에서 부모 함수에서 선언 된 변수는 내부 함수에서 액세스 할 수 있습니다.

그러나 closures in a loop에는 클로저 변수의 동일한 인스턴스가 루프 내에서 생성 된 모든 내부 함수간에 공유되기 때문에 내부 함수가 호출 될 때 변수에 할당 된 마지막 값을 가져옵니다. 루프.

솔루션은 여기에 일부 답변이 이미 문제가 명시 적 폐쇄로 해결 될 수있는 방법을 설명했다

directionsService = new google.maps.DirectionsService(); 
for (var i = 0; i < routes.length; i++) { 
    (function (idx) { 
     var dir_request = { 
      origin: new google.maps.LatLng(routes[idx]['start_lat'], routes[idx]['stop_lng']), 
      destination: new google.maps.LatLng(routes[idx]['end_lat'], routes[idx]['end_lng']), 
      travelMode: google.maps.TravelMode.WALKING 
     }; 
     directionsService.route(dir_request, function (result, status) { 
      // the variable idx will refer to the array index for the current iteration 
      if (status == google.maps.DirectionsStatus.OK) { 
       // render with custom logic depending on which route this is here 
      } 
     }) 
    })(i) 
} 
+0

감사합니다. 매우 도움이됩니다. – Catherine

0

Marka가 맞습니다. 이상한 일이 발생하지 않는 한 모든 함수 변수는 콜백 function(result,status)에서 사용할 수 있습니다. 설명 및 몇 가지 예는 here을 참조하십시오. dir_request을 알고 있기 때문에 콜백을 만들 때 콜백 코드에서 직접 참조 할 수 있습니다. routes 어레이에 액세스해야하는 경우 i을 참조 할 수 있어야합니다.

function makeCallback(dir_request) { 
    return function(result,status) { 
     //your code, and you can refer to dir_request 
    }; 
} 

다음

directionsService.route(dir_request, makeCallback(dir_request)); 

전화 나는 그리스 몽키 스크립트에 한 번 그렇게했다 : 당신이에서 값을 받고 어떤 문제가있는 경우

, 당신은 간접 레이어를 추가하는 시도 할 수 있습니다 function()을 만들 때 필요한 변수가 잠겨 있는지 확인하십시오.

+0

생각하지만 :

function createRouteCallback(route) { return function (result, status) { if(status == google.maps.DirectionsStatus.OK) { // render with custom logic depending on which route this is here //you can just use route here console.log(route); } }; } 

그런 다음 루프에서 간단히 할 수있는 인덱스에서 응답을 반환 할 때까지 경로를 요청 했습니까? 사실 Arun P. Johny가 아래에서 설명하는 것과 정확히 같습니다. – Catherine

+0

@ 캐서린 아니,이 답변에서 제안 된 해결책은 실제로 Arun P. Jhonny가 제안한 것보다 낫습니다. 단지 설명이 잘되어 있지 않고 올바른 변수를 덮지 않습니다. 내 대답의 편집을 참조하십시오. – plalx

1

아래와 같이 루프 내부 로컬 폐쇄를 만드는 것입니다. Function.prototype.bind을 사용하는 또 다른 예가 있습니다.

directionsService.route(dir_request, (function(result, status) { 
    //the this keyword now refers to the correct route object 
    console.log(this); 

    if(status == google.maps.DirectionsStatus.OK){ 
     // render with custom logic depending on which route this is here 
    } 
}).bind(routes[i])); 

편집 :

여기 bind없이 그것을 할 다른 방법이 효율적이다. 루프에서 범위 안전 함수를 인라인하는 것은 모든 반복에서 새 루프를 작성해야하므로 효율적이지 않습니다. 그 목적을 위해 함수를 만들고 다시 사용하는 것이 좋습니다.내가, 내 배열을 통해 내가 다른 일에있어 인덱스를하지 않을 반복하고있어 경우

directionsService.route(dir_request, createRouteCallback(routes[i])); 
+0

그래, 나는 별도의 기능을 가지고 있다고 생각했지만 인라인으로 할 수있는 방법을 알고 싶었다. 감사! – Catherine

관련 문제