How to use javascript namespaces correctly in a View / PartialView

杀马特。学长 韩版系。学妹 提交于 2019-12-01 20:43:54

As a matter of safety/best practice, you should always use the module pattern. If you also use event handlers rather than shoving javascript into the onclick attribute, you don't have to worry about naming conflicts and your js is easier to read:

<script type="text/javascript">
(function() {
    // your button selector may be different
    $("input[type='submit'].button").click(function(ev) {
        DisableInputsForSubmit();

        if ($('#EditParameters').validate().form()) {  
            SetContentArea(GetHtmlDisplay('SaveParameters', 'Area','Controller'), $('#Parameters').serialize());
        } 
        ev.preventDefault();
    });

    function DisableInputsForSubmit() {
        if ($('#IsDisabled').is(':checked')) {
            $('#Parameters :input').attr('disabled', true);
        } else {
            $('#Parameters :input').removeAttr('disabled');
        }
    }
})();
</script>

This is trivially easy to extract into an external file if you decide to.

Edit in response to comment:

To make a function re-usable, I would just use a namespace, yes. Something like this:

(function() {

    MyNS = MyNS || {};

    MyNS.DisableInputsForSubmit = function() {
        //yada yada
    }

})();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!