2019-10-25 (작성자: 곽빛나라)
-
문제점
mounted() { console.log("mounted() 실행"); this.loadMap(); this.getList() console.log("mounted 실행 끝 : "+this.map) },
-
처음 mounted(){}에서 getList() 내 drawMarker()를 호출할 때, map 객체 정보가 없음, 하지만 mounted 이후 addMarker() 내 drawMarker()를 호출할 경우 map객체정보가 있음
-
loadMap()의 실행이 끝나기 전에 drawMarker()가 실행됨
-
-
해결
-
loadMap() 코드 수정
-
원래 코드
loadMap() { const _this = this; if (navigator.geolocation) { // GPS를 지원하면 navigator.geolocation.getCurrentPosition(function (position) { var mapContainer = document.getElementById('map') // 지도를 생성한다 var map = new kakao.maps.Map(mapContainer, mapOption); _this.currentlatlng = map.getCenter(); kakao.maps.event.addListener(map, 'dragend', function () { _this.currentlatlng = map.getCenter(); }); _this.map = map; }, function (error) { console.error(error); }) console.log("loadMap() if문 끝 : " + _this.map) } else { alert('GPS를 지원하지 않습니다'); } console.log("loadMap() 실행 끝 : " + _this.map) },
-
수정 후 코드
getCurrentGPS() { const _this = this; if (navigator.geolocation) { // GPS를 지원하면 navigator.geolocation.getCurrentPosition(function (position) { _this.loadMap(position); _this.getList(); _this.drawMarker(); }, function (error) { console.error(error); }) console.log("getCurrentGPS() if문 끝 : " + _this.map) } else { alert('GPS를 지원하지 않습니다'); } console.log("getCurrentGPS() 실행 끝 : " + _this.map) },
-
-
-
필요한 지식
-
콜백함수 : 어떤 이벤트가 발생한 후, 수행될 함수를 의미함
다른 함수가 실행을 끝낸 뒤 실행되는(call back)되는 함수
-
콜백함수가 필요한 이유
- 자바스크립트는 이벤트 기반 언어이기 때문->자바스크립트는 다음 명령어를 실행하기 전 이전 명렁어의 응답을 기다리기보단, 다른 이벤트들을 기다리며 계속 명령을 수행함
-
콜백함수 사용시 this객체 유의해야함 : 콜백함수 내에서 this는 전역 객체인 window가 되기 때문
-