굳이 저 방법을 해야한다면 아래와 같이
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) 자기 자신을 리턴하는 로직은 잘 쓰지 않기 때문입니다.
모르는 사람이 읽다 보면 코드 흐름을 따라가다가 멈칫하게 만드는 부분이라서요.
하지만 우리에겐 주석이 있으니!! 잘만 적어두면 전혀 문제가 없을거라 봅니다.