2012-09-29 32 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。它像任何表達是可能的。 –