2011-12-02 2 views
11

아래 코드가있는 경우 새로운 직렬 버튼을 여러 번 누르면 serial 클래스의 텍스트 상자가 이벤트에 두 번 이상 바인딩됩니다.jQuery에서 여러 번 이벤트를 바인딩하면 효과가 발생합니까?

jQuery는 바인딩 메소드가 여러 번 호출 되더라도 이벤트를 한 번만 등록합니까?

$(document).ready(function() { 

    MonitorSerialTextBoxes(); 

    $('#newSerial').click(function() { 

     $.tmpl("productTemplate", mymodel).insertAfter($(".entry").last()); 
     MonitorSerialTextBoxes(); 

    }); 

    function MonitorSerialTextBoxes() { 
     $('.serial').each(function() { 
     // Save current value of element 
     $(this).data('oldVal', $(this).val()); 

     // Look for changes in the value 
     $(this).bind("propertychange keyup input paste", function (event) { 

     // If value has changed... 
     if ($(this).data('oldVal') != $(this).val() && $(this).val().length == 10) { 

      // Updated stored value 
      $(this).data('oldVal', $(this).val()); 

      // Do action 
     } 
     }); 
    } 

}); 

UPDATE : 나는 그래서 MonitorSerialTextBoxes 기능 수정 thiings에 아래 코드를 추가 할 것으로 예상? JQuery와 문서에서

$('.serial').unbind("propertychange keyup input paste"); 

:

여러 핸들러 등록이있는 경우, 그들은 항상 당신은 여러 이벤트 처리기를 바인딩 할 수 있습니다

+1

테스트하지 않고 답을 잘 모르겠지만 Visual Event로 직접 테스트 해 볼 수 있습니다. http://www.sprymedia.co.uk/article/Visual+Event 페이지의 지침을 따르십시오. –

답변

12

가 결합 된 순서대로 실행됩니다 단일 요소. 두 온 클릭 이벤트와 버튼을 생성 할 것이다 다음

$("button").bind("click", myhandler); 
$("button").bind("click", myhandler); 

하나의 옵션이 먼저 이벤트를 바인딩을 해제하는 것입니다 : 이것은 단지 하나의 바인딩 클릭 이벤트가 발생합니다

$("button").unbind("click").bind("click", myhandler); 
$("button").unbind("click").bind("click", myhandler); 

.

양식에 동적으로 요소가 추가되어 이벤트를 리 바인드하는 경우 이벤트가 아직 존재하지 않을 수있는 요소에 바인딩 할 수있는 live() 또는 새 on()을 조사하는 것이 좋습니다. 예 : 웹킷 개발자 도구 (사파리와 크롬), 당신은 다음, 그것을 검사 원소 패널의 오른쪽 창에서 아래로 스크롤하여 요소에 결합되어 어떤 이벤트를 볼 수 있습니다에서

$("button").live("click", myhandler); // All buttons (now and in 
             // the future) have this handler. 

. 'Event Listeners'라는 축소 가능한 상자 아래에 있습니다. 방화 광케이크는 비슷한 기능을해야합니다.

+5

jQuery 버전 1.7 이상인 경우 ['.live()'] (http://api.jquery.com/live/) 메소드 대신 ['.on()']을 사용하십시오 (http : //api.jquery.com/on/) (당신이 언급 한),하지만 버전 1.4 이상에서도 ['.delegate()'] (http://api.jquery.com/delegate)를 사용하는 것이 좋습니다. .live()보다는 오히려. – nnnnnn

2

글쎄, 이벤트가 여러 번 묶이기 때문에 오버 헤드가 많이 발생하고 문제가 발생한다고 생각합니다. 이 간단한 바이올린 봐 : http://jsfiddle.net/nicolapeluchetti/syvDu/

<button id='newSerial'>Button</button> 
<div class='serial'>Serial</div> 
<div class='serial'>Serial</div> 
<div class='serial'>Serial</div> 

MonitorSerialTextBoxes(); 

$('#newSerial').click(function() { 
    MonitorSerialTextBoxes(); 

}); 

function MonitorSerialTextBoxes() { 
    $('.serial').each(function() { 


     // Look for changes in the value 
     $(this).bind("click", function(event) { 
      alert("hi"); 
     }); 
    }); 
} 

당신은 당신이 사업부를 클릭하면 하나의 alòert가 표시되는 페이지를로드하지만, 때마다 당신은 새로운 이벤트가

을 연결되어 있기 때문에 한 번 더 경고가 표시되는 버튼을 누르면
관련 문제