How to use javascript namespaces correctly in a View / PartialView

后端 未结 1 1800
南笙
南笙 2021-01-20 03:00

i\'ve been playing with MVC for a while now, but since the project i\'m on is starting to get wind in its sails more and more people are added to it. Since i\'m in charge of

相关标签:
1条回答
  • 2021-01-20 03:45

    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
        }
    
    })();
    
    0 讨论(0)
提交回复
热议问题