프론트엔드
wiselotis frontend
  • Calendar(달력)


    개발을 시작한지 얼마 안되었을때
    회사에서 프로젝트를 진행하면서 javascript 달력을 만들었는데
    오늘 보니 코드가 아주 더럽다.
    좀더 깔끔하게 코드도 바꾸고 기능도 추가해 달력을 구현해 보았다.

    먼저 달력구현을 위해 객체를 만들었다.
    참고
    https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Date
    https://msdn.microsoft.com/ko-kr/library/4d4x3w61(v=vs.94).aspx

    Calendar

        
    
        //Calendar 객체
        function Calendar(newDate){
          if(newDate == null){
            this.date = new Date();
          }
          this.date = newDate;
          this.set = function(newDate) {
            this.date = newDate;
          };
          this.get = function() {
            return this.date;
          };
          this.getLongTime = function() {
            return this.date.getTime();
          };
          this.setLongTime = function(millisec) {
            return this.date.setTime(millisec);
          };
          this.setTxtTime = function(time_txt){
            var time = time_txt.split(":");
            this.date.setHours(time[0]);
            this.date.setMinutes(time[1]);
            this.date.setSeconds(time[2]);
          }
          this.getTxtTime = function(){
            return this.date.setHours() + ":" + this.date.setMinutes() +":" +this.date.setSeconds();
          }
          this.addDay = function( day ) {
            this.setLongTime(this.getLongTime() + day * 86400000);
          }
          this.getYear = function() {
            return this.date.getFullYear();
          };
          this.setYear = function(year) {
            this.date.setFullYear(year);
          };
    
          this.getMonth = function() {
            return this.date.getMonth()+1;
          };
          this.setMonth = function(month) {
            this.date.setMonth(month-1);
          };
          this.getDayOfMonth = function() {
            return this.date.getDate();
          };
          this.setDayOfMonth = function(dayOfMonth) {
            this.date.setDate(dayOfMonth);
          };
    
          this.setDayOfWeek = function(dayOfWeek) {
            var day = dayOfWeek - this.date.getDay();
            this.addDay(day);
          };
          this.getDayOfWeek = function() {
            return this.date.getDay();
          };
    
          this.getLastDay = function(){
            return new Date(this.date.getFullYear(), (this.date.getMonth())+1, 0);
          }
          this.getStartDay = function(){
            return new Date(this.date.getFullYear(), this.date.getMonth(), 1);
          }
          this.setDate = function( year, month, dayOfMonth ) {
            this.setYear(year);
            this.setMonth(month);
            this.setDayOfMonth(dayOfMonth);
          };
    
          this.getyyyyMMdd = function() { return this.getYear() + "-" + filling(this.getMonth(), 2) + "-" + filling(this.getDayOfMonth(), 2); };
    
          var filling = function(value, length) {
            var result = "" + value;
            for( var step = result.length; step < length; step++ ) {
              result = "0" + result;
            }
            return result;
          }
        }
        
        

    Date 객체

    new Date(); new Date(value); new Date(dateString); new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
    선언시 주의할 점 1. dateString은 규격이 있는데, 브라우저나 언어에서 이 규격을 따르긴 하는데 구현할 때 차이가 있어서 완~~전! 스트레스를 받는다. 얼마전에도 화면에서 앱으로 date를 넘기면서 앱에서 dateString으로 date를 선언하는 과정에서 버그가 있었다. 개발할 때 주의할 필요가 있겠다. 2. Date는 literal을 지원하지 않아 무조건 new 연산자를 이용해 생성해야한다. 3. 하나이상의 파라미터의 경우 local시를 기반으로 처리 된다. UTC UTC는 협정 세계시로 그리니치 평균시에 기반한다. GMT = 국제원자시 + 윤초(자전 주기가 일정하지 않기 때문에 세계시 UT1과 0.9초의 차이가 생길 때 협정 세계시에서는 하루의 마지막 1분을 59초나 61초로 해서 이 차이를 수정한다.) 메소드 Date객체는 요주의 인물(메소드)들이 몇있는데 얘네를 잘 이해해야 날짜의 지배자가 될 수 있다. (* 알쏭달쏭 주의 *) - value: 기준, 1970년 1월 1일 00:00:00 부터의 시간을 밀리초 단위로 표현한 정수값. 윤초는 무시한다. - getYear : 2018 / 08 / 23 기준 118 이 값으로 반환된다 이 값은 1900을 뺀 값이다.진정으로 원하는 2018 을 얻고 싶다면 getFullYear를 사용해야 한다. - getDay : 요일을 [0-6] 의 수로 반환한다. 주의 할점은! 현지화된 플랫폼에서 다르게 반환 될 수 있는데 우리나라의 경우 0: 일요일 이지만 영국 독일의 경우 0은 월요일을 뜻한다. - getLastDay : 실제로 이런 메소드는 없지만 달력을 구현할 때 필요해서 만들어 두었다. new 를 이용해서 Date를 선언할 때 day 를 0으로 선언하면 전달의 마지막 날이 된다.
    예를 들어,
    day = [1-31]
    new Date(2018, 7, 0) >> 2018.7.31 이 된다.
    30일인 달을 선언 할 때 31로 선언하면 다음달의 1일이 된다. (그 달의 첫날은 굳이 이런식으로 알아 낼 필요가 없지만.. )
    new Date(2018, 5, 31) >> 2018.7.01
    참고로 year = [0-11]
    new Date(2018,12,1) >> 2019.01.01 이 된다 변환 date를 string으로 변환하는 방식에는 세가지 방식이 있다. 1. ISO 8601 확장 형식에 따른 변환 >> toISOString() : 2018-08-26T08:52:04.894Z 2. GMT 표준 시간대 기준에 따른 변환 >> toGMTString() : Sun, 26 Aug 2018 08:52:04 GMT 3. 시스템 설정에 근거한 변환(지역에 따라 다름) >> toLocaleString() : 2018. 8. 26. 오후 5:52:04 우리나라는 세계 표준시와 9시간의 차이가 있기 때문에 사용시 주의해야한다. 현재 시간을 string으로 input을 셋팅할때 더욱 유의해야함. (사용자가 수첩을 입력할때 입력한 시간이 자동으로 입력되게 했는데(valueAsDate = date객체 를 사용했었다.), 9시 이전일 경우 전날에 입력한것으로 저장이 되었다. )

    > 이 포스트 더보기
  • 내/외국인 주민등록번호 검증 로직 적용 / 정규식

    이번에 외국인 사용자가 추가 되면서 유효성 검사를 새로 수정했다. 화면에서는 검증 로직을 반영해서 하드하게 validation체크를 하고 서버단에서는 정규식을 이용해서 숫자만 체크할 수 있도록 했다.

    ##javascript

    CODE <div class="collapse_wrapper"> <div class="collapse" id="basic"> <div class="card">

     var validatePersonalNo = function(personalNo) {
     		var strXxx = "234567892345";
     		var intMagicKey = 11;
     		var intModeNum = 11;
     		var intKey = 0;
     		if (personalNo.length != 13) return false;
     		for (var i = 0; i < strXxx.length; i++) {
     			intKey += parseInt(personalNo.charAt(i)) * parseInt(strXxx.charAt(i));
     		}
     		if("5678".match(personalNo.charAt(6))){
     			//외국인일 경우 13
     			intMagicKey = 13;
     		}
     		intKey = intMagicKey - (intKey % intModeNum);
     		if(intKey > 9){
     			intKey-=10;
     		}
     		return (intKey  == personalNo.charAt(12)) ? true : false;
     	};
     
    </div> </div> </div>

    정규식

      if(!personalNo.matches("^(?:[0-9]{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[1,2][0-9]|3[0,1]))-?[1-6][0-9]{6}$")){
        throw new **exception("주민등록번호가 올바르지 않습니다.");
      }
    
    

    > 이 포스트 더보기
  • JsReport: ios에서 history.go(-1) 버그

    JavaScript Report

    history.go(-1) 사용 시 웹 브라우저에서는 아무 문제가 없지만 ios 웹뷰에서 뒤로가기가 되지 않고 하얀 화면이 나오는 경우가 있음.
    특정 경우에 about:blank가 떨어지게 되는데
    원인은 정확히 알 수 없음.
    웹뷰에서 window history에 문제가 있는 모양임.
    정확히는
    a,b,c 메뉴가 있는데
    a - > b -> c 이런식으로 location.href 를 이용해서 페이지를 이동시켰다.
    문제는 a->b -> a -> b -> c 이렇게 갔을 때는 뒤로가기가 정상적으로 됐는데
    a->b->c 이렇게 c 메뉴에 갔다가 뒤로가기를 할경우에 하얀화면이 뜨는것이었다.
    테스트 해봤지만 정확한 원인을 찾지 못했음.
    그래서
    b에서 c로 페이지 이동전에
    replaceState를 이용해서 history에 돌아올 url을 정상적으로
    넣어주었더니 되돌아 올때 하얗게 되는 현상이 없어졌다. ( b 페이지에 .. )
    뭔가 페이지 이동할때 history가 깨지는 것 같다. (왜일까… )

    var path = window.location.href;
    var ua = navigator.userAgent.toLowerCase(),
    version = 0;
    if( this.isIos() ){
    version = parseFloat(ua.substr(ua.search(/ipad|iphone/), 30).match(/\d+_+\d/)[0].replace('_', '.'));
    if( version >= 9.3 ){
    window.history.replaceState({}, "title" , path );
    }
    }

    https://developer.mozilla.org/en-US/docs/Web/API/History_API

    이방법은 살짝 꼼수라고 할 수 있는 듯.
    정확한 원인은 시간있을때 알아봐야겠다 .

    > 이 포스트 더보기
[frontend]의 더 많은 Post 보기
top