jQuery Plugin 기초
원문참조 http://learn.jquery.com/plugins/
$() 함수는 파라미터로 전달된 정보를 기반으로 jQuery 오브젝트를 생성하고 리턴하는데, 리턴된 jQuery 오브젝트를 이용하면 많은 기능을 가진 메소드를 사용할 수 있게 된다.
자바스크립트의 객체와 함수
자바스크립트에서 함수는 원칙적으로 객체이다. 즉, 함수 오브젝트라는 말을 사용할 수 있다는 것이다.
아래의 예를 보면, Eclipse에서 자바스크립트를 작성할 때 함수 이름 뒤에 점을 입력하고, CTRL+SPACE 를 누르면 그 참조를 통해 다양한 함수를 사용할 수 있다는 것을 알 수 있다
위에서 알 수 있는 사실을 바탕으로 다음과 같은 코드를 작성하고 테스트해보면 예상대로 실행되는 것을 확인할 수 있다
function myFunc() {
alert('myFunc() is invoked');
};
function myFunc2($) { // $는 함수의 파라미터 변수이다
$();
};
function btnClick() {
myFunc2(myFunc); //함수의 이름을 다른 함수의 파라미터로 전달한다
}
</script>
</head>
<body>
<input type="button" value="테스트" onClick="btnClick();">
</body>
</html>
window.alert() 함수도 alert 라는 함수 오브젝트에 해당하므로 아래와 같이 사용될 수도 있다.
function myFunc2($) {
$('Hello');
};
function btnClick() {
myFunc2(alert);
}
</script>
</head>
<body>
<div id="div1" style="background-color:orange;width:100px;height:20px;"></div>
<button id="btStop">STOP</button>
<input type="button" value="테스트" onClick="btnClick();">
</body>
</html>
jQuery에서 '$' 는 'jQuery' 라는 함수 오브젝트의 별칭이므로 jQuery()와 $() 는 동일한 표현이라고 할 수 있다.
jQuery 에서 사용자 정의 함수 선언하기
jQuery 함수 오브젝트에는 fn 이라는 오브젝트를 내장하고 있는데, fn 오브젝트에는 jQuery에서 사용되는 모든 메소드가 선언되어 있다.
$()에서 리턴된 객체를 통해 호출할 수 있는 메소드는 $.fn 이라는 오브젝트로부터 메소드를 가져와서 실행하므로 사용자가 jQuery 메소드를 정의하고자 한다면 $.fn 에 함수를 등록해야 한다.
아래의 사이트를 인용하여 사용자 정의 함수 선언 및 사용 예를 보자
http://learn.jquery.com/plugins/basic-plugin-creation/
$.fn.greenify = function() {
this.css( "color", "green" );
};
$( "a" ).greenify(); // Makes all the links green.
메소드 체이닝(Method Chaining)을 위하여 위의 내용은 아래와 같이 변경하여 사용할 수도 있다.
참고로, 함수 안에서 this 키워드는 jQuery 오브젝트의 함수 안에서 사용되는 상황이므로 $(this)와 같은 표현을 사용하지 않더라도 이미 jQuery 오브젝트 메소드 안에서 사용되므로 this 는 그 자체만으로 jQuery 오브젝트이다.
$.fn.greenify = function() {
this.css( "color", "green" );
return this;
}
$( "a" ).greenify().addClass( "greenified" );
jQuery 함수 오브젝트의 별칭으로 사용되는 '$' 는 jQuery가 아닌 다른 라이브러리에서도 변수명으로 얼마든지 사용될 수 있기 때문에 주의하지 않으면 작성된 프로그램이 오작동할 가능성이 있다. 그러므로 위의 예처럼 $를 사용할 때 함수 밖에서 사용한다면 다른 라이브러리의 $변수와 충돌하여 오작동할 수 있다는 것이다. 아래의 예처럼 함수 안에서 지역변수로 사용한다면 지역변수가 우선이므로 다른 라이브러리와 충돌하는 상황을 예방할 수 있다.
(function ( $ ) {
$.fn.greenify = function() {
this.css( "color", "green" );
return this;
};
$.ltrim = function( str ) {
return str.replace( /^\s+/, "" );
};
$.rtrim = function( str ) {
return str.replace( /\s+$/, "" );
};
}( jQuery ));
위의 예제에서는 즉시실행함수(Immediately Invoked Function)를 사용했는데, 여기서 즉시실행함수의 역할은 $를 파라미터 변수로 선언하여 jQuery 함수 오브젝트의 참조를 저장하게 되므로 다른 라이브러리에서 $변수를 사용하더라도 이 영역에서는 $변수가 jQuery 함수 오브젝트로 사용되고 있는 것을 확실하게 보장하게 되는 것이다.
또한 위의 예제에서는 $.fn을 사용하지 않고 $에 바로 함수를 등록한 것을 볼 수 있는데, 이는 jQuery에서 Utility 함수라고 부르고 DOM 오브젝트와 연관성이 없는 공통적인 기능을 구현할 때 주로 사용된다. jQuery 의 Utility 함수를 일반적으로 전역함수라고도 부른다
Utility 함수는 사용할 때 '$.함수명()' 과 같이 호출할 수 있다.
Utility 함수는 선언할 때 다른 함수명과 중복될 가능성이 더 높기 때문에 다음과 같은 방법을 사용하여 함수명이 중복되는 것을 방지할 수 있다.
(function( $ ) {
$.myUtils = {
utilA : function() { },
utilB : function() { }
};
})( jQuery );
다음은 현재시간을 DIV 태그에 출력하는 커스텀 함수를 작성해본 것이다
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>jQuery Custom Function</title>
<style type="text/css">
body { text-align: center;}
</style>
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
(function( $ ){
$.fn.timeDisplay = function() {
// there's no need to do $(this) because
// "this" is already a jquery object
// $(this) would be the same as $($('#element'));
var node = this;
var timerID = window.setInterval(function(){
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
node.text(h+':'+m+':'+s);
},1000);
return timerID;
};
$.fn.timeClear = function(timerID) {
clearInterval(timerID);
return this;
};
})( jQuery );
});
var intTimer;
function onStart() {
intTimer = $('#div1').timeDisplay();
}
function onStop(){
$('#div1').timeClear(intTimer);
}
</script>
</head>
<body>
<div id="div1" style="background-color:orange;width:100px;height:20px;"></div>
<button id="btStart" onClick="onStart();">START</button>
<button id="btStop" onClick="onStop();">STOP</button>
</body>
</html>
위에서 작성된 jQuery 커스텀 함수를 별도의 파일에 저장하면 다른 곳에서 재활용할 수 있도록 배포할 수 있다.
jquery 플러그인의 파일명을 정할 때는 다음과 같은 권장사항을 따르도록 한다
jquery.플러그인 이름-버전값.js
예를 들어, jquery.timeDisplay-1.0.js 과 같이 지정하면 된다.
위에서 생성한 플러그인(jquery.timeDisplay-1.0.js) 테스트
작성된 커스텀 함수를 별도로 분리하여 파일(jquery.timeDisplay-1.0.js)에 저장한다
$(document).ready(function() {
(function( $ ){
$.fn.timeDisplay = function() {
// there's no need to do $(this) because
// "this" is already a jquery object
// $(this) would be the same as $($('#element'));
var node = this;
var timerID = window.setInterval(function(){
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
node.text(h+':'+m+':'+s);
},1000);
return timerID;
};
$.fn.timeClear = function(timerID) {
clearInterval(timerID);
return this;
};
})( jQuery );
});
위의 플러그인을 사용하는 예
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>jQuery Custom Function</title>
<style type="text/css">
body { text-align: center;}
</style>
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="jquery.timeDisplay-1.0.js"></script>
<script type="text/javascript">
var intTimer;
function onStart() {
intTimer = $('#div1').timeDisplay();
}
function onStop(){
$('#div1').timeClear(intTimer);
}
</script>
</head>
<body>
<div id="div1" style="background-color:orange;width:100px;height:20px;"></div>
<button id="btStart" onClick="onStart();">START</button>
<button id="btStop" onClick="onStop();">STOP</button>
</body>
</html>