객체지향 프로그래밍 목적 : 코드를 깔끔하게 복잡하지 않게 정리하는것
refactoring : 과거의 코드를 효율적으로 바꾸는 것
object를 통해 template 정리
template라는 객체를 만들고 객체 안에서 property를 정의
<기존 코드>
function templateHTML(title, list, body, control){
return `
<!doctype html>
<html>
<head>
<title>WEB1 - ${title}</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="/">WEB</a></h1>
${list}
${control}
${body}
</body>
</html>
`;
}
function templateList(filelist){
var list = '<ul>';
var i = 0;
while(i < filelist.length){
list = list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
i = i + 1;
}
list = list+'</ul>';
return list;
}
<수정 코드>
var template = {
HTML:function(title, list, body, control){
return `
<!doctype html>
<html>
<head>
<title>WEB1 - ${title}</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="/">WEB</a></h1>
${list}
${control}
${body}
</body>
</html>
`; },
list:function(filelist){
var list = '<ul>';
var i = 0;
while(i < filelist.length){
list = list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
i = i + 1;
}
list = list+'</ul>';
return list;
}
}
위 template를 사용하는 부분 수정
templateList을 template.list로 변경
templateHTML을 template.HTML으로 변경하고 template라고 되어있는 변수를 html로 수정
예시( 주석: 기존코드)
/* var list = templateList(filelist);
var template = templateHTML(title, list,
`<h2>${title}</h2>${description}`,
`<a href="/create">create</a>`
);
response.writeHead(200);
response.end(template);
*/
var list = template.list(filelist);
var html = template.HTML(title, list,
`<h2>${title}</h2>${description}`,
`<a href="/create">create</a>`
);
response.writeHead(200);
response.end(html);
'Web > Node.js' 카테고리의 다른 글
[Node.js] Module 사용 (0) | 2020.08.02 |
---|---|
[Node.js] 글 삭제 (0) | 2020.07.31 |
[Node.js] 글 수정 (0) | 2020.07.31 |
[Node.js] 글 생성 (0) | 2020.07.31 |
[Node.js] Package Manger (0) | 2020.07.30 |