2011-10-06 11 views
5

私の関数は、データ属性に基づいてフィルタリング(配列)された項目のリストを返します。これをチェーン化可能なjquery関数にするにはどうすればよいですか?

私は、この関数はチェーン可能にすることができれば、私はそれをしたいと思います:

filterSvcType("hosting").fadeOut(); 

私はこれをどのように行うのですか。私は何をしたいか

$(document).ready(function(){ 
    function filterSvcType (svcType) { 
     var selectedServices = $("#service-list div"); 
     var chose = selectedServices.filter(function() { 
      return $(this).data("service-type") == svcType; 
     }); 

     console.log(chose);    
    } 
    filterSvcType("hosting");  
}); 

はこのようにそれを呼び出すのですか?

答えて

9

あなたが追加する必要があるすべてはあなたのconsole.log呼び出しの後return chose;です。

しかし、あなたはまた、あなたが呼び出すことができるjQueryプラグイン

(function($) { 
    $.fn.filterServiceType = function(svcType){ 
     return this.filter(function(){ 
      return $(this).data("service-type") == svcType; 
     }); 
    }; 
})(jQuery); 

にこれを回すことができるもう少しjQueryishある

$('#service-list div').filterSvcType('hosting').fadeOut(); 

として。

+0

awesome!それをプラグインにする方法を私に示すためのボーナスポイント。それをやろうとしていただけだった –

1

あなたはただこれは、すべてのjQueryのメソッドで使われている同じ原理である

$(document).ready(function(){ 
    function filterSvcType (svcType) { 
     var selectedServices = $("#service-list div"); 
     var chose = selectedServices.filter(function() { 
      return $(this).data("service-type") == svcType; 
     }); 
     return chose; 
     console.log(chose);    
    } 
    filterSvcType("hosting").fadeOut();  
}); 

あなたのフィルタ要素を返すことができます。彼らはあなたが送るセレクタやコレクションに何らかのロジックを行い、そのコレクションを戻します。だから今あなたがすることができます:

var filtered = filterSvcType("hosting"); 
filtered.fadeOut(); 

本当にチェーンと同じです。

Here's a quick test to show it in action

関連する問題