2012-09-29 4 views
0

저는 jquery/jqueryui를 처음 접했지만 빠르게 진행 중입니다. 중복 코드가 많아서 리팩터링 할 수있는 방법이 있어야합니다.jqueryui 위젯의 오버로드 메서드

그래서 예를 들어 나는 자동 완성 위젯의 모두가 하나 같이 가지 정의가 : 그들은 함수를 호출을 다시 변경을 제외하고

$("#workOrderSearchCustomer") 
    .autocomplete({ 
     source: function(request, response) { 
      $.getJSON("/autocomplete/customers", { 
      term: acExtractLast(request.term) 
      }, response) 
     }, 
     search: function() { 
      // custom minLength 
      var term = acExtractLast(this.value); 
      if (term.length < 2) { 
      return false; 
      } 
     }, 
     focus: function() { 
      // prevent value inserted on focus 
      return false; 
     }, 
     select: function(event, ui) { 
      var terms = acSplit(this.value); 
      // remove the current input 
      terms.pop(); 
      // add the selected item 
      terms.push(ui.item.value); 
      // add placeholder to get the comma-and-space at the end 
      terms.push(""); 
      this.value = terms.join(", "); 

      // update the search 
      searchAndReloadWorkorderTabs(); 
      return false; 
     } 
}); 

그들은 모두 동일한 코드를 사용하고 자동 완성 콘텐츠의 위치 . 이 경우 위젯을 위젯에서 변경 것들 "/ 자동 완성/고객"과 searchAndReloadWorkorderTabs()는 단지입니다

내가 좋아하는 뭔가를 할 수 있도록하고 싶습니다 :

$("#workOrderSearchCustomer") 
    .autocomplete(initAutoComplete( 
     "autocomplete/customers", 
     searchAndReloadWorkorderTabs 
    )); 

을 그리고이 채우기가 모든 메소드에서 변경되는 두 가지만 변경하므로이 중복 코드를 모두 가질 필요가 없습니다. 이것을 해결하는 표준 방법은 무엇입니까?

답변

1

구성 개체를 구성하는 기능을 소개 할 수 있습니다. 기본적으로 코드와 같지만 함수의 종료에서 매개 변수를 가져옵니다. 호출은 귀하의 질문에 표시됩니다.

function initAutoComplete(endpointURI, callbackFunction){ 
    return { 
     source: function(request, response) { 
      $.getJSON(endpointURI, { 
      term: acExtractLast(request.term) 
      }, response) 
     }, 
     search: function() { 
      // custom minLength 
      var term = acExtractLast(this.value); 
      if (term.length < 2) { 
      return false; 
      } 
     }, 
     focus: function() { 
      // prevent value inserted on focus 
      return false; 
     }, 
     select: function(event, ui) { 
      var terms = acSplit(this.value); 
      // remove the current input 
      terms.pop(); 
      // add the selected item 
      terms.push(ui.item.value); 
      // add placeholder to get the comma-and-space at the end 
      terms.push(""); 
      this.value = terms.join(", "); 

      // update the search 
      callbackFunction(); 
      return false; 
     } 
    } 
} 
+0

훌륭한 작품! Javascript 그것 폭탄. 그 어떤 표현도 가능합니다. –