본문 바로가기

Programming/JQuery

jQuery Event - .bind() & .unbind()

jQuery Event - .bind() & .unbind()

.bind() 요소에 이벤트 핸들러를 지정
.unbind() 지정된 이벤트 핸들러를 삭제

 

[ .bind( eventType [, eventData] , handler(eventObject)) ]

.bind() 메소드는 말 그대로 개체와 이벤트를 묶어주는 역할을 한다.

.bind( eventType [, eventData], handler(eventObject) )
eventType
하나 이상의 DOM 이벤트를 표현하는 문자열. "click", "submit," 또는 사용자가 만든 함수들(사용자정의함수).
eventData 이벤트 핸들러에 전달하기 위한 데이터 집합(map of data).
handler(eventObject) 이벤트와 함께 실행될 함수
.bind( eventType [, eventData], preventBubble )
eventType
하나 이상의 DOM 이벤트를 표현하는 문자열. "click", "submit," 또는 사용자가 만든 함수들(사용자정의함수).
eventData 이벤트 핸들러에 전달하기 위한 데이터 집합(map of data).
preventBubble false를 세번째 인자로 설정하면 발생하는 기본 액션을 방지하고 버블링(bubbling)에서 이벤트를 중지시키는 기능이 구현됩니다.
.bind( events )
events
실행될 하나 이상의 DOM 이벤트과 함수 집합

앞에서 진행한 event 관련 메서드의 경우 해당 메소드를 직접 호출하지만, bind()의 경우 파라미터의 값으로 이벤트 이름을 넣음 으로써 해당 이벤트를 체크하게 된다.

$("div").click(function() { alert('click;); });

일반적인 .click 이벤트

$("div").bind('click', function() { alert('click'); });

.bind를 사용하였을 경우 (.click 이벤트가 직접적으로 사용되지 않고, 이벤트의 이름만('click') 사용

 

공백으로 구분된 여러 가지의 이벤트를 연결 할 수도 있다.

$('#foo').bind('mouseenter mouseleave', function() {
    alert($(this).text());
});

위와 같이 eventType이 들어가는 곳에 공백으로 여러가지의 이벤트를 지정하여 사용 할 수 있다. foo라 명명된 곳에 마우스 포인터를 이동하거나 나올때 경고창이 발생한다.

참고적으로, jQuery 1.4버전 이전에서는 위와 같이 여러가지의 이벤트를 지정하기 위해 아래와 같이 적용하였다.

$('#foo').bind({
  click: function() {
    // do something on click
  },
  mouseenter: function() {
    // do something on mouseenter
  }
});

 

[ .bind() 이벤트 사용 예제 ]

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>jQuery</title>    
    <style>
        p { background:yellow; font-weight:bold; cursor:pointer; padding:5px; }
        p.over { background: #ccc; }
        span { color:red; }
    </style>

    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">
    $(document).ready(function () {
        $("p").bind("click", function(event){
            var str = "( " + event.pageX + ", " + event.pageY + " )";
            $("span").text("Click happened! " + str);
        });

        $("p").bind("dblclick", function(){
            $("span").text("Double-click happened in " + this.nodeName);
        });

        $("p").bind("mouseenter mouseleave", function(event){
            $("span").text("mouse enter or leave");
        });
    });
    </script>
</head>
<body style="padding:10px;">
<p>Click or double click here.</p>
<span></span>
</body>
</html>

    <script type="text/javascript">
    $(document).ready(function () {
        $("p").bind("click dblclick mouseenter mouseleave", function(event){
            if(event.type == "click"){
                var str = "( " + event.pageX + ", " + event.pageY + " )";
                $("span").text("Click happened! " + str);
            }else if(event.type == "dblclick"){
                $("span").text("Double-click happened in " + this.nodeName); 
            }else{
                $("span").text("mouse enter or leave"); 
            }
        });
    });
    </script>

위와 같이 e의 type을 확인 한 후에 이벤트 타입을 구분해준 후 사용해도 무방하다.
(위의 소스와 실행은 동일하다.)

 

[ .unbind( [eventType] [, handler(eventObject)]) ]

bind() 함수로 바인딩한 이벤트 핸들러를 해제하기 위해서 .unbind() 를 사용한다. (jQuery 1.7 부터는, .on().off() 함수로 대체되었다.) 간단한 경우에는, 인자없이 .unbind() 를 사용하여 요소의 모든 이벤트의 바인딩을 해제한다.

.unbind( [eventType] [, handler(eventObject)] )
  eventType
JavaScript click 또는 submit 같은 이벤트 타입을 표현하는 문자열
  handler(eventObject) 더 이상 실행되지 않을 기능
.unbind( eventType, false )
  eventType
JavaScript click 또는 submit 같은 이벤트 타입을 표현하는 문자열
  false .bind( eventType, false ) 바인딩에 대응하여 바인딩 해제를 위해 반환할 값 'false'
.unbind( event )
  event
이벤트 핸들러에 전달된 JavaScript 이벤트 객체

간단하게 생각해서 .bind()이벤트의 반대라고 생각하면 된다.

$('#foo').unbind();
$('#foo').unbind('click');

위의 소스는 모든 이벤트에 대하여 unbind시키는 것이고, 아래의 소스는 click이벤트를 모두 unbind시킨다.

간단하게 위와 같이 사용하면 되지만 모든 혹은 특정 이벤트에 대하여 unbind()이벤트를 지정하는 것은 좋지 않다. 왜냐하면 만일 같은 요소에 같은 이벤트가 바인딩되어 있었다면 그것 마저도 모두 바인딩이 제거되게 되기 때문이다.

var handler = function() {
    alert('The quick brown fox jumps over the lazy dog.');
};
$('#foo').bind('click', handler);
$('#foo').unbind('click', handler);

그리고 위의 소스와 같이 특정 핸들러를 지정하여 bind 혹은 unbind 할 수 있다.

 

[ .unbind() 이벤트 사용 예제 ]

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>jQuery</title>   
    <style>
        button { margin:5px; }
        button#theone { color:red; background:yellow; }
    </style>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">
        function aClick() {
            $("div").show().fadeOut("slow");
        }

        $(document).ready(function () {
            $("#bind").click(function () {
                 // $("#theone").bind('click', aClick) 로 사용해도 된다. 
                 $("#theone").click(aClick)
            .text("Can Click!");
            });

            $("#unbind").click(function () {
                $("#theone").unbind('click', aClick)
                .text("Can't Click");
            });

       });
      </script>
</head>
<body style="padding:10px;">
    <button id="theone">Does nothing...</button>
    <button id="bind">Bind Click</button>
    <button id="unbind">Unbind Click</button>

    <div style="display:none;">Click!</div>
</body>
</html>

원본 : http://www.sqler.com/390805, http://kli.wincom.co.kr/kli_home/ajaxSample/test2.jsp

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

jQuery Event - Browser Events  (0) 2012.04.26
jQuery Event - .one() & .live() & .die()  (0) 2012.04.24
jQuery Event - Document loading  (0) 2012.04.24
jQuery Event - Form Events  (0) 2012.04.24
jQuery Event - Keyboard Events  (0) 2012.04.23