我已经开始学习 javascript 模块模式,并且我有以下代码:
// 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,
    };
}());
为了使这段代码工作,我必须调用init视图中的方法,如下所示:
<script>
    $(document).ready(function() {
        PersonallInformation.init();
    })        
</script>
是否可以避免调用init视图?
更新: 我用以下方式重写了它:
function library(module) {
    $(function() {
        if (module.init) {
            module.init();
        }
    });
    return module;
}
var PersonallInformation = library(function () {
...