How do I make this into a chainable jquery function?
Asked Answered
G

2

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?

Guibert answered 6/10, 2011 at 8:34 Comment(0)
H
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.

Hedges answered 6/10, 2011 at 8:39 Comment(1)
awesome! bonus points for showing me how to turn it into a plugin. Was just trying to do thatGuibert
P
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

Pearlypearman answered 6/10, 2011 at 8:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.