프로젝트를 리펙토링하면서 JQuery에서 꼭 좀 개선하고 싶은 부분이 있었다.

중복되는 함수에 대해 하나의 js파일에 담아두고 필요한 곳에서 호출해 사용하게 하고 싶었다.

 

예를들어 jQuery를 통해 하나의 테이블을 만들어야 된다고 가정.

function tableStr(arr) {
    let str = "<table class=\"table\">" + 
                  "<thead>" +
                      "<tr>" +
                          "<th>header1</th>" + 
                          "<th>header2</th>" + 
                          "<th>header3</th>" +
                      "</tr>" +
                  "</thead>" + 
                  "<tbody>";
    
    $(arr).each(function(i, attach) {
        str += "<tr>" +
                   "<td>" + arr.body1 + "</td>" +
                   "<td>" + arr.body2 + "</td>" +
                   "<td>" + arr.body3 + "</td>" +
               "</tr>";
    }
    
    str += "</tbody>" +
           "</table>";
    
    return str;
}

 

이렇게 데이터를 받아 테이블을 파싱하는 코드가 여러곳에 존재한다고 하면, 각각의 js 파일에 중복되어 작성되게 된다.

그럼 가장 좋은 방법은 이 tableStr 이라는 함수를 하나의 js 파일에 분리하거나 필요한 곳 중 한군데에만 작성해두고 그 함수를 호출하는 것이 가장 좋은 방법일 것.

 

처리는 js 파일을 새로 만들고 그 안에 함수를 작성한 뒤 필요한 곳에서 호출하게 했다.

 

필요한 곳을 parent1.js, parent2.js 라고 가정하고 분리해서 작성한 곳을 child1.js로 가정한다.

//parent1.js
function setTable() {
    $.getJSON("/getTableData", function(arr) {
        let str = jQuery.tableStr(arr);
        $(".formDiv").append(str);
    }
}

//parent2.js
function setTable() {
    $.getJSON("/getBoardTableData", function(arr) {
        let str = jQuery.tableStr(arr);
        $(".formDiv").append(str);
    }
}


//child1.js
jQuery.tableStr = function(arr) {
    let str = "<table class=\"table\">" + 
                  "<thead>" +
                      "<tr>" +
                          "<th>header1</th>" + 
                          "<th>header2</th>" + 
                          "<th>header3</th>" +
                      "</tr>" +
                  "</thead>" + 
                  "<tbody>";
    
    $(arr).each(function(i, attach) {
        str += "<tr>" +
                   "<td>" + arr.body1 + "</td>" +
                   "<td>" + arr.body2 + "</td>" +
                   "<td>" + arr.body3 + "</td>" +
               "</tr>";
    }
    
    str += "</tbody>" +
           "</table>";
    
    return str;
}

 

방법은 위와 같다.

호출되는 함수는 jQuery.함수명 = function() { } 이런 구조로 작성하면 되고, 호출할때는 jQuery.함수명 으로 호출하면 된다.

여기서 주의사항.

해당 html 혹은 jsp 파일에 parent, child가 모두 들어가있어야 한다.

 

<html>
....
<script type="text/javascript" src="/js/parent1.js"></script>
<script type="text/javascript" src="/js/child1.js"></script>
....

이렇게 되어있다면 정상적으로 호출해서 사용할 수 있다.

 

'Front > JQuery' 카테고리의 다른 글

JQuery(비동기방식연동 Ajax)  (0) 2020.05.26
JQuery(애니메이션 효과 제어 메소드)  (0) 2020.05.26
JQuery(효과 및 애니메이션 메소드)  (0) 2020.05.22
JQuery(그룹이벤트)  (0) 2020.05.22
JQuery(이벤트 객체)  (0) 2020.05.22

+ Recent posts