5

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?

Tatu Ulmanen
  • 123,288
  • 34
  • 187
  • 185
Amit Erandole
  • 11,995
  • 23
  • 65
  • 103

2 Answers2

9

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.

Jamiec
  • 133,658
  • 13
  • 134
  • 193
1

You can just return your filtered elements

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

This is the same principle that's being used on all jQuery methods. They do some logic to whatever selector and/or collection you send in, and then return that collection back. So now you could do:

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

Which is the same as chaining, really.

Here's a quick test to show it in action

peirix
  • 36,512
  • 23
  • 96
  • 126