Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I've started using this JavaScript pattern. Is there anything wrong with it?

Tags:

javascript

I've started using this pattern in JavaScript. I'm not sure if I read about it specifically, or if I just conjured it up one day.

The format is...

var name = (function() {

    var init = function() {
       // Init something
       $('a').click(show);
    };

    var show = function() {
       // Show something
    };

    $(init);

})();

And here is a real world example...

var contactForm = (function() {
    var init = function() {

         if ( ! $('body').hasClass('contact')) {
            return;
         };

         var form = $('.contact #content form');

         form.validate({
              rules: {
                  'full-name': {
                      required: true
                  },    
                  'email': {
                      required: true,
                      email: true
                  },    
              },
              messages: {
                  'email': {
                      email: 'Please make sure this email is valid.'
                  }

          }
          }); 

    };

    $(init);

})();

Is there anything wrong with this?

like image 536
alex Avatar asked Dec 10 '10 01:12

alex


1 Answers

No YUI actually call this the Module pattern and uses it in alot of their code.

You might even do the following within the anonymous function.

name = new init();
like image 83
stevebot Avatar answered Sep 22 '22 11:09

stevebot