Question

I know the switch case statement is inherent to javascript and you can't change it. I'm still learning javascript and jQuery so I can get by, but I don't know enough to write something that might be on the level of jQuery itself. So, take this as an idea or a question about if this idea is feasible.

This is my idea, a switch case statement that can use objects... which can be used something like this:

switch( $(this) ){

 case .hasClass('foo'):
  // do something
  break;

 case .filter('.bar').attr('id') == 'foo':
  // do something else
  break;

}

Edit: Even something like this would be nice (possibly a more reasonable idea)...

switch ($(this).hasClass()) {

 case 'foo':
  alert('found a foo!');
  break;

 case 'bar':
  alert('found a bar!');
  break;

}
Was it helpful?

Solution

Often switches are not the best way to solve a problem, but using jQuery you could make a plugin that works kind of like a switch statement:

(function($) {
    $.fn.switchClasses = function(switches) {
        return this.each(function() {
            var that = this;
            $.each(this.attr("class").split(' '), function(i, class) {
                var func = switches[class];
                if(func)
                    func.apply(that, class);
            });
        });
    };
})(jQuery);

You would use the plugin like so:

$(this).switchClasses(
    {
        "class1":
        function(class) {
            // Do something for this class, 
            // the "this" variable is the jquery object that matched the class
        },

        "class2":
        function(class) {

        }
    }
);

OTHER TIPS

First, the switch statement only works on int's. I'm not sure why javascript kept this limitation from C/C++, but it is there.

Using nested if-then-else blocks instead of a switch can lead to highly unreadable code, if you're dealing with more than a handful of options.

However, just like in C and C++, there are workarounds, and this one involves using "break" like a goto, which are not always evil. This is a situation (a large amount of nested if-the-else's) where goto would make the code more efficient and readable. In C/C++ you would implement this using goto's with the label being at the end of the series of if's (where the end of switch bracket is now), and skip jumping into a switch context.

switch (1) { //yes, that is a hardcoded 1, we only want the switch block for the break keyword
    if (yourString == "Case 1") {
        do_stuff_1();
        break; // well, we're done, let's get out of here.
    }

//implicit else - if you matched the first one, you'd be out of here

    if (yourString == "Case 2") {
        do_stuff_2();
        break; // well, we're done, let's get out of here.
    }

    // etc.....

    default:
        do_error_condition();
} //end of switch

What is wrong with a normal if/else?

inst = $(this);

if (inst.hasClass('foo')) {
    // do something
} else if (inst.filter('.bar').attr('id') == 'foo') {
    // do something else
}

You can switch on element.attr('class') if you're dealing with one class name.

If you're dealing with more than one you can do element.attr('class').split(/\s+/) and check for the classes name in that array.

I also think you might want to take a look at .is(). You can do things like if( element.is('a.foo') ) console.log( 'This is a link with a 'foo' class.' );

You might want to change your approach though. I can't see this being the most efficient way to do what you're trying to do.

    (function($) {
    $.fn.switchClasses = function(switches) {
        return this.each(function() {
            var that = this;
            $.each(this.attr("class").split(' '), function(i, classname) {
                var func = switches[classname];
                if(func){
                    func.apply(that, classname);
                }
            });
        });
    };
})(jQuery);

'class' is a reserved name, and I added some missing parenthesis

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top