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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With