JQuery 이해하기
JQuery를 이해하기 위해 직접 만들어보는 Query
window.kQuery=function(arg){//arg = selector, function, dom Node
if(typeof arg == 'string'){
//css selector
let elementNodeList =document.querySelectorAll(arg);
if(!elementNodeList)elementNodeList=[];//list가 없으면 []초기화
let jqueryWrapperObject = {
'elementNodeList':elementNodeList,
'css':function(propertyName,propertyValue){
for(let i=0; i<this.elementNodeList.length;i++){
this.elementNodeList[i].style.cssText=`${propertyName}:${propertyValue}`;
}
return this;
},
'text':function(textArg){
if(!textArg){//falsy, getter
let returnText="";
for(let i=0; i<this.elementNodeList.length;i++){
returnText+=this.elementNodeList[i].innerHTML;
}
return returnText;
}else{//setter
for(let i =0; i<this.elementNodeList.length;i++){
this.elementNodeList[i].innerHTML=textArg;
}
return this;
}
}
};
return jqueryWrapperObject;
}
if(typeof arg == 'function'){
/*
인자로 대입된 함수를 DOM 트리 생성직후에 호출되도록
window.onload 이벤트 프로퍼티에 등록
*/
window.addEventListener('load',arg);
}
if(typeof arg == 'object'){
//dom node
}
if(typeof arg == 'undefined'){
//arg가 없을때
}
}
/****Jquery[$] global function */
kQuery.each=function(array, functionArg){
for(let i=0;i<array.length;i++){
functionArg(i,array[i]);
}
};
window.$=window.kQuery;
window에 kQuery 라는 펑션 프로퍼티를 등록한다.
이 kQuery 펑션은 파라메터를 받을 수 있다.
window.kQuery=function(arg){
}
파라메터를 받은 후 파라메터의 타입을 구분해 타입에 따라 처리하는게 달라진다.
if(typeof arg == 'string'){
//css selector
let elementNodeList =document.querySelectorAll(arg);
if(!elementNodeList)elementNodeList=[];//list가 없으면 []초기화
let jqueryWrapperObject = {
'elementNodeList':elementNodeList,
'css':function(propertyName,propertyValue){
for(let i=0; i<this.elementNodeList.length;i++){
this.elementNodeList[i].style.cssText=`${propertyName}:${propertyValue}`;
}
return this;
},
'text':function(textArg){
if(!textArg){//falsy, getter
let returnText="";
for(let i=0; i<this.elementNodeList.length;i++){
returnText+=this.elementNodeList[i].innerHTML;
}
return returnText;
}else{//setter
for(let i =0; i<this.elementNodeList.length;i++){
this.elementNodeList[i].innerHTML=textArg;
}
return this;
}
}
};
return jqueryWrapperObject;
}
css selector에 들어갈 선택자 String이 입력되면
선택된 노드들을 WrapperNode로 만들고
다양한 함수를 사용할 수 있게 WrapperNode에 함수들을 붙여준다.
위 예제에서는 text()를 get하거나 set하는 text()함수와 css를 변경해주는 css()함수를 만들었고
css()함수는 wrapper 객체의 css를 변경해준뒤 다시 반환해준다.
text()함수는 인자가 없는 경우 객체의 text를 반환하고 인자가 있는 경우 객체의 text를 인자의 string으로 바꾼뒤 반환해준다.
if(typeof arg == 'function'){
/*
인자로 대입된 함수를 DOM 트리 생성직후에 호출되도록
window.onload 이벤트 프로퍼티에 등록
*/
window.addEventListener('load',arg);
}
만약 함수가 kQuery에 인자로 들어온다면 인자로 대입된 함수를 onload 이벤트 프로퍼티에 등록한다.
kQuery.each=function(array, functionArg){
for(let i=0;i<array.length;i++){
functionArg(i,array[i]);
}
};
kQuery가 가지는 함수를 정의해준다. 위 예제는 반복문을 정의하였다.
kQuery.each(array,function(){});
사용할 때는 kQuery에 바로 each 함수를 호출하여 반복할 array와 함수를 인자로 대입해준다.
window.$=window.kQuery;
JQuery는 $로도 사용하는데
window.$에 kQuery를 등록하면 kQuery도 $로 사용할 수 있다.