2011-04-25 9 views
0

본질적으로 서버 측에서 테이블을 정렬하고 컨테이너에 내용을 다시 넣는 플러그인이 있습니다. 부모 폼 제출을 호출하기 위해 표 머리글 셀에 클릭 이벤트를 추가하는 바인딩 함수가 있습니다. 나는 이것이 최선의 방법이 아니라고 생각한다. 어떤 아이디어?jQuery :이 작업을 수행하는보다 효율적인 방법이 있습니까?

$.fn.myplugin = function() { 
    return this.each(function() { 
    var parentform = $(this).parents("form"); 
    var tableidentifier = $(this).attr("id"); 

    var bindclicks = function() { 
     parentform.find("table#" + tableidentifier + " thead tr th").click(function() { 
     // Some code to change the sort column- boring! 
     parentform.submit(); 
     }); 
    } 

    bindclicks(); 

    parentform.submit(function() { 
     $.post(parentform.attr("action"), parentform.serialize(), function(res) { 
     parentform.find("table#" + tableidentifier).replaceWith($(res)); 
     bindclicks(); 
     }) 
     return false; 
    }); 
    }); 
} 

나는 내가 그 이벤트를 바인드를 다시 다시 호출하고 replaceWith()를하고있는 중이 야하기 때문에 다음, 최대 클릭 핸들러를 설정하기 위해 먼저 bindclicks() 함수를 호출합니다. 그것은 작동하지만 궁금 해요 ..이 대신

답변

3

.delegate()을 사용할 수 있으므로 매번 클릭 핸들러를 리 바인드 할 필요가 없습니다. 와

$.fn.myplugin = function() { 
    return this.each(function() { 
     var parentform = $(this).parents("form"); 
     var tableidentifier = $(this).attr("id"); 

     parentform.delegate("table#" + tableidentifier + " thead tr th", "click", function() { 
      parentform.submit(); 
     }); 

     parentform.submit(function() { 
      $.post(parentform.attr("action"), parentform.serialize(), function(res) { 
       parentform.find("table#" + tableidentifier).replaceWith($(res)); 
      }) 
      return false; 
     }); 
    }); 
} 

그냥 싹둑 - 당신이 <table/>를 교체하기 때문에,이 일을해야 표시 및 위임 된 이벤트가 내가`$에 동일한 코드를 게시 할 필요가 없습니다겠습니까 <form/>

+0

+1, '델리게이트'가가는 길 –

+0

쿨! 'delegate' 함수를 절대로 사용하지 마십시오. 매우 편리합니다. – Wells

0

:

var bindclicks = function() { 
     parentform.find("table#" + tableidentifier + " thead tr th").click(function() { 
      parentform.submit(); 
     }); 
    } 

    bindclicks(); 

이보십시오 :

$("table#" + tableidentifier + " thead tr th", parentForm) 
    .bind('click', function() { 
     parentForm.submit(); 
    }); 

대신 bindlive를 사용하는 경우는 클릭 처리기를 바인딩합니다 새로 생성 된 요소에 적용됩니다.

+0

에 바인딩 .post' 콜백 폼 제출 후? – Wells

관련 문제