I have started learning the javascript module pattern and I have the following code:
// PersonalInformation.js
var PersonallInformation = (function () {
$.validator.addMethod("checkPhoneNumber", function (value, element) {
if (!value) return true;
return /^((\+7)|8)(700|701|702|705|707|712|713|717|718,721|725|726|727|777)[0-9]{7}$/.test(value);
}, "Wrong phone format");
function updateQTip() {
$('div.invalid_form').qtip({
content: function (api) {
var text = $(this).prev();
return "<div class='tip_cont'><span class='simple cost'><span class='corner'></span>" + $(text).attr('data-description') + "</span></div>";
},
position: {
target: 'mouse',
adjust: { x: 5, y: 17 }
},
style: {
tip: { corner: false }
}
});
}
function updateError() {
$('.invalid_form').closest('.wrap_input').addClass('error');
$('#reg_form_pay input').each(function(element) {
if ($(this).hasClass('invalid_form')) {
$(this).closest('.wrap_input').addClass('error');
} else {
$(this).closest('.wrap_input').removeClass('error');
}
});
updateQTip();
}
function validateForm() {
$("#reg_form_pay").validate({
rules: {
Email: { required: true, email: true },
PhoneNumber: { required: true, checkPhoneNumber: true },
FirstName: { required: true },
Surname: { required: true }
},
messages: {
Email: '',
PhoneNumber: '',
FirstName: '',
Surname: ''
},
errorClass: "invalid_form",
errorElement: "div",
errorPlacement: function (error, element) {
error.insertAfter(element);
},
onkeyup: false,
showErrors: function (errorMap, errorList) {
this.defaultShowErrors();
updateError();
}
});
}
function privateInit() {
validateForm();
console.log('init ok');
}
return {
init: privateInit,
};
}());
To make this code work I have to call the init method in the view as follows:
<script>
$(document).ready(function() {
PersonallInformation.init();
})
</script>
Is it possible to avoid having to call init in the view?
UPDATE:
I have rewritten it in the following way:
function library(module) {
$(function() {
if (module.init) {
module.init();
}
});
return module;
}
var PersonallInformation = library(function () {
...
The short answer is no
your validateForm method uses the DOM to do it’s work. If you call the init method prior to document.ready the behavior is unspecified.
You will have to call some method in document.ready.
You are not really using the module partern since you are in effect just encapsulating function in another function so you would have the same kind of encapsulation if you moved the entire code between (function (){…}()) to document.ready in which case you could change the last part of the function to
Ie inline the init function.
EDIT
A rewrite could be something like:
and you’d then call it like: