daum.maps.event.addListener 즉시실행함수

안녕하세요.
이 질문은 API와는 관련이 없습니다.
소중한 시간 빼앗을까 걱정되지만 조심스럽게 글 씁니다.

daum.maps.event.addListener(map, 'idle', function() {
  // 액션
});

위 '액션’을 로드할 때, 한번 실행시키고, idle 이벤트에 추가 시키고 싶어서…

daum.maps.event.addListener(map, 'idle', (function() {
  // 액션
})());

이런 무리수도 해보았는데… 방법이 없을까 싶습니다.

실제로 코드 일부는 아래와 같습니다.

getCurrentPosition().then(function (res) {
  let position = new daum.maps.LatLng(res.latitude, res.longitude);
  map.setCenter(position);
}).catch(function (err) {
  console.error(err);
}).finally(function () {
  $('.loading').fadeOut('slow');
  
  daum.maps.event.addListener(map, 'idle', function() {
    // 이전 요청 취소
    if (typeof cancel === 'function') {
      cancel();
    }

    // 클러스터 객체 제거
    for (var key in cluster) {
      cluster[key].setMap(null);
    }
  
    // 클러스터 배열 초기화
    cluster = [];
  
    $('.progress').fadeIn('slow');
      getNearbyChargingStation().then(function (res) {
      console.log(res);
    
      // @ 샘플 클러스터 표시
      cluster[cluster.length] = new daum.maps.CustomOverlay({
        map: map,
        content: '<div class="cluster">333</div>',
        position: map.getCenter()
      });
    }).catch(function (err) {
      console.error(err);
    }).finally(function () {
      $('.progress').fadeOut('slow');
    });
  });
});

1번. 맵을 띄운다.
2번. 현재 위치를 가져온다.
3번. 현재 위치 주변 데이터를 가져온다.
4번. 데이터를 뿌린다.

이 때 ‘3번’, '4번’는 idle 이벤트에 추가…

처음 ‘1번’, ‘2번’ 후 '3번, '4번’이 진행되고
이 후 idle 이벤트로 ‘3번’, '4번’이 진행됐으면 합니다만…

가장 쉬운 방법으로는…
안에 내용을 함수로 만들어서 idle 이벤트 내 함수 호출, ‘2번’ 진행 후 후 함수 호출
이거밖에 없나합니다… 프론트엔드 고ㅈ라서 웁니다…

이미 답을 알고 계시네요. :slight_smile:

굳이 저 방법을 해야한다면 아래와 같이
idle 핸들러 함수(Function Expression)에 이름을 주어(eg. showStations)
자기 자신을 리턴하는 함수로 만들면 됩니다.

getCurrentPosition().then(function (res) {
  let position = new daum.maps.LatLng(res.latitude, res.longitude);
  map.setCenter(position);
}).catch(function (err) {
  console.error(err);
}).finally(function () {
  $('.loading').fadeOut('slow');
  
  daum.maps.event.addListener(map, 'idle', function showStations () {
    // 이전 요청 취소
    if (typeof cancel === 'function') {
      cancel();
    }

    // 클러스터 객체 제거
    for (var key in cluster) {
      cluster[key].setMap(null);
    }
  
    // 클러스터 배열 초기화
    cluster = [];
  
    $('.progress').fadeIn('slow');
      getNearbyChargingStation().then(function (res) {
      console.log(res);
    
      // @ 샘플 클러스터 표시
      cluster[cluster.length] = new daum.maps.CustomOverlay({
        map: map,
        content: '<div class="cluster">333</div>',
        position: map.getCenter()
      });
    }).catch(function (err) {
      console.error(err);
    }).finally(function () {
      $('.progress').fadeOut('slow');
    });
    return showStations;
  }());
});

이렇게 즉시실행함수(IIFE)로 못할 것은 없지만,
굳이 가독성을 해치면서까지 그럴 필요가 있을까 싶습니다.

말씀하셨듯, 주변 데이터를 가져오는 로직을 빼서
따로 함수 선언(Function Declaration)을 하시고(eg. showStations)
메인 함수에서 사용하시는게 깔끔합니다.

function showStations () {
  // 이전 요청 취소
  if (typeof cancel === 'function') {
    cancel();
  }

  // 클러스터 객체 제거
  for (var key in cluster) {
    cluster[key].setMap(null);
  }
    
  // 클러스터 배열 초기화
  cluster = [];
    
  $('.progress').fadeIn('slow');
    getNearbyChargingStation().then(function (res) {
    console.log(res);

    // @ 샘플 클러스터 표시
    cluster[cluster.length] = new daum.maps.CustomOverlay({
      map: map,
      content: '<div class="cluster">333</div>',
      position: map.getCenter()
    });
  }).catch(function (err) {
    console.error(err);
  }).finally(function () {
    $('.progress').fadeOut('slow');
  });
}

getCurrentPosition().then(function (res) {
  let position = new daum.maps.LatLng(res.latitude, res.longitude);
  map.setCenter(position);
}).catch(function (err) {
  console.error(err);
}).finally(function () {
  $('.loading').fadeOut('slow');
  
  daum.maps.event.addListener(map, 'idle', showStations);
  showStations();
});

가독성을 언급한 건,
보통은 FE에 이름을 주어(named function) 자기 자신을 리턴하는 로직은 잘 쓰지 않기 때문입니다.
모르는 사람이 읽다 보면 코드 흐름을 따라가다가 멈칫하게 만드는 부분이라서요.
하지만 우리에겐 주석이 있으니!! 잘만 적어두면 전혀 문제가 없을거라 봅니다.

그래서 위에는 후자를 좋은 것처럼 써놨지만
결론은 개취임…

1개의 좋아요

ㅋㅋㅋㅋㅋㅋㅋㅋ 항상 답변 감사드립니다. ^^
카카오엔 훌륭한 개발자분들이 많으실 것 같네요.
깊이있게 개발 이야기 나눌 분들이 많을 것 같아 부럽습니다.