Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Partial View clearing scripts Jquery Ajax

Project: Asp.NET Core 2.1

Working on a dashboard project that has a side nav that's divides into sub side's etc. On the right side there is a "main view" where the partial should be loaded, so when the partial is selected it should be rendered on the right-hand side.

I have accomplished all of this, but when I have 2 different views with some javascript that is equal, like a variable, I then get an error for redeclaring, this is because the last script loaded is still cached. Anyone knows how to attack this problem?

The variables for the partial are also declared in the file and not separate, have tried to separate also, but this didn't work.

Thinking about just not loading this Ajax, but I like the smoothness of it.

Example

View1:

<div>
  <h1>Hello View1</h1>
  <script>
  const myVar1 = 'Hello';
  </script>
<div>

View2:

<div>
  <h6>Hello View2</h6>
  <script>
  const myVar1 = 'Hello';
  </script>
</div>

Error: redeclaration of myVar1.

Thanks in advance!

like image 298
Mojo Avatar asked Oct 02 '18 12:10

Mojo


1 Answers

What you need is a namespace. JavaScript doesn't use the namespace keyword. What is used instead is closures. You cannot control the variable names especially when it is not your code. Try this:

Example

View1:

<div>
    <h1>Hello View1</h1>
    <script>
        var cl1 = (function(e){
            const myVar1 = 'closure 1'; // No public access.
            return {
                myVar1:myVar1, // Assign public access to cl1.myVar1.
                vname:function(){return myVar1; } // or assign it as a getter.
            };
        })();
    </script>
<div>

View2:

<div>
    <h6>Hello View2</h6>
    <script>
        var cl2 = (function(){
            const myVar1 = 'closure 2';
            return {
                myVar1:myVar1,
                vname:function(){return myVar1; }
            };
        })();
    </script>
</div>

Test the output:

  <script>
    console.log('cl1.myVar1', cl1.myVar1, cl1.vname());
    console.log('cl2.myVar1', cl2.myVar1, cl2.vname());
  </script>

It results in:

cl1.myVar1 closure 1 closure 1
cl2.myVar1 closure 2 closure 2
like image 142
943A Avatar answered Nov 17 '22 03:11

943A