views:

858

answers:

4

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;

}
A: 

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
}
Andrew Hare
Readability after more than one or two cases ?
VirtualBlackFox
A: 

Please note that I really don't recommend this.

var $this=$(this);
switch( true ){

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

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

}
I wouldn't want to use the switch of "true" either, I was hoping more for something like the second example I added above.
fudgey
+2  A: 

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) {

        }
    }
);
joshperry
I always loved using object literals as quick switch statements. +1
gnarf
A: 

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.

BIllium