views:

49

answers:

5

Silly question I think, but is there a way to use the "if" statement as a reusable function

    success: function(msg){
     if(msg=='o'){
        $j('#ok').show();
        $j(button).show();
        $j('#chk').hide();
        }
    else{
        $j('#ok').hide();
        $j('#chk').show();
        $j(button).hide();
        }

    }

I have a number of times when I want to call it and I would rather have a "smaller" weight.

+1  A: 
success: function(msg){
     doStuff(msg);

    }

function doStuff()
{
   if(msg=='o'){
        $j('#ok').show();
        $j(button).show();
        $j('#chk').hide();
    }
    else{
        $j('#ok').hide();
        $j('#chk').show();
        $j(button).hide();
    }
}
skyfoot
Or just use doStuff for the value of success directly.
Shog9
@Shog9 good point.
skyfoot
+1  A: 

Sure. Not silly at all.

success: function(msg){
    checkMsg( msg );
}

...

function checkMsg( msg ) {
    if(msg=='o'){
        $j('#ok').show();
        $j(button).show();
        $j('#chk').hide();
    } else {
        $j('#ok').hide();
        $j('#chk').show();
        $j(button).hide();
    }
}

I assume button is a variable that was created outside the scope of the success: callback.

patrick dw
As @Shog9 noted in a comment, if the `success:` callback doesn't need to do anything else, then you could simply use the function reference as the value directly. `success: checkMsg`
patrick dw
A: 

I don't understand you question. If you mean you want to checkthe condition alot just put the if statement in a function.

Ash Burlaczenko
+1  A: 

This technique employs 'closures' to generate a function to provide as a success method:

function doStuffGenerator( button ){ 
  return function( msg ){ 
    if(msg=='o'){
        $j('#ok').show();
        $j(button).show();
        $j('#chk').hide();
    }
    else{
        $j('#ok').hide();
        $j('#chk').show();
        $j(button).hide();
    }
  };
}

...
jQuery.ajax({ 
   ...
   success: doStuffGenerator( button )
   ...
});
Kent Fredric
A: 

Another way to write functions in jQuery is this:

var myFxn = function(param){
  // do function stuff here
}

var myOtherFxn = function(param){
  // do function stuff here
}

so in your code:

if(msg=='o'){
  myFxn();
} else {
  myOtherFxn();
}
scubacoder