Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make this into a chainable jquery function?

My function returns a filtered (array) list of items based on the data attribute.

I would like it if I could make this function chainable:

$(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");       
});

What I want to do is call it like this:

filterSvcType("hosting").fadeOut(); 

How do I do this?

like image 506
Amit Erandole Avatar asked Oct 06 '11 08:10

Amit Erandole


1 Answers

All you need to add is return chose; after your console.log call.

But you could also turn this into a jQuery plugin

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

Then you can call as

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

Which is a bit more jQueryish.

like image 139
Jamiec Avatar answered Sep 28 '22 14:09

Jamiec