Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript global variable when using Scripts.Render MVC4

I have an MVC 4 project that utilizes javascript bundling.

In my _Layout.cshtml page I have something like this:

    @Scripts.Render("~/bundles/scripts/desktop/modernizr",
        "~/bundles/scripts/desktop/jquery","~/bundles/scripts/desktop/jqueryui",
        "~/bundles/scripts/desktop/jqueryvalidation", "~/bundles/scripts/custom")

There are others, but this is just an example. Within one of my scripts that's called in the custom script I need to reference a global variable that set within the ready function, as shown below:

  <script type="text/javascript">                   
     $(function () {            
         //alert('Page is ready!');
         var warning = 10;
         var timeout = 20;   }); </script>     

Problem is, I always seem to get an error within the method that requires the warning and timeout variables. Am I missing something obvious (not to me, though!) on how I should create these variables? Should I var them outside the $Ready, because the js is loading before the page is technically ready?

Where should the global variable go, if everything is already in a render bundle and there are no script blocks?

Thanks!

like image 556
RichieMN Avatar asked Jul 29 '26 05:07

RichieMN


1 Answers

The warning and timeout variables aren't global. They've only been defined within the function that you provide to the $ function.

I'd generally recommend avoiding global variables where possible, but if you really want to create global variables just use this:

<script type="text/javascript">
   var warning = 10;
   var timeout = 20; 
</script>     

Or this:

<script type="text/javascript">
   $(function () {
       window.warning = 10;
       window.timeout = 20;   
   });
</script>     
like image 195
p.s.w.g Avatar answered Jul 31 '26 19:07

p.s.w.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!