Tutorial :Jquery “reusable” function



Question:

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.


Solution:1

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 )     ...  });  


Solution:2

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


Solution:3

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.


Solution:4

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »