-3

I've been reading up on anonymous javascript functions and have a general question about using them with event listeners via jquery.

I have the following event listener that will do some stuff upon the submission of a form.

if(sky === 'blue') {
    $('#my-form').on('submit', function(){
        //do some stuff
        $('#my-div').show();
    })
}

Would it make any difference (i.e., pros & cons, things that could go wrong, etc.) if I were to declare it as-is in my javascript file or should I be wrapping it in an anonymous function like so

 $(function() {
    if(sky === 'blue') {
    //do my stuff
 }

Any input is appreciated, thanks!

Clay Banks
  • 4,483
  • 15
  • 71
  • 143

1 Answers1

2

If you're not declaring any vars or functions and you make sure your code will execute after the dom is ready it doesn't make any difference.

BUT the common experience is that maybe you are sure those premises are true now, but someday somebody will break one of them, then you'll propably have a problem (a leak, a conflict, whatever).

As an advice, I would tell you to wrap your code into a Immediately-Invoked Function Expression (IIFE).

gfpacheco
  • 2,831
  • 2
  • 33
  • 50