RON2015
RON2015

Reputation: 443

JSP Page Imports / Javascript Object

The issue I am having involves server side (JSP) so I can't put together a jFiddle example but I will do my best to demonstrate the issue as simply as I can here:

First, I have a JSP page which at the top of the page I import a javascript file which holds a javascript class that is used a variable amount of times on the page.

So the following (import A) gets imported at the top of the JSP page for use within the page content:

<script>
    var TheJSClass = function(aValue, bValue) {
     var me = this;
     this.somePropertyA = aValue;
     this.somePropertyB = bValue;
     this.showValues = function() {
      console.log("me.somePropertyA = " + me.somePropertyA);
      console.log("me.somePropertyB = " + me.somePropertyB);
     }
    }
</script>

so on the JSP page there is just some HTML:

<ul>

  <li> blah blah blah 
    <!-- jsp import B here -->
  </li>

  <li> blah2 blah2 blah2
    <!-- jsp import B here -->
  </li>

</ul>

The following is an example for import B

<!-- the unique_id is an attribute set on the page that I increment here at the top of this (import B) file this was my attempt to differentiate between the instances of the class within import A-->
<script>
 var info<%=unique_id%> = new TheJSCLass(10,20);
</script>
<a href="" onclick="info<%=unique_id%>.showValues();">Try Me</a>

this all seems to work....The problem happens when I add multiple imports... For example, the following:

<!-- Another Import B -->

    <script>
     var info<%=unique_id%> = new TheJSCLass(30,40);
    </script>
    <a href="" onclick="info<%=unique_id%>.showValues();">Try Me</a>

and then another:

<!-- Another Import B -->

    <script>
     var info<%=unique_id%> = new TheJSCLass(60,70);
    </script>
    <a href="" onclick="info<%=unique_id%>.showValues();">Try Me</a>

The problem is, that every "Try Me" button shows the values from the last import, so they will all show 60 70 as the values... Am I going about this all wrong? Any advice? Thanks for everyone's time.


EDIT: I just made this jFiddle which has everything except for JSP adding the number to each variable name and it works fine:

https://jsfiddle.net/vzo4fmjt/

So is it something to do with the JSP number that I am adding to the variable name during each import?

Upvotes: 0

Views: 113

Answers (1)

RON2015
RON2015

Reputation: 443

Thank you everyone who tried to see what was going wrong. It turned out that I was doing something incredibly stupid. In my real file, the "var me = this;" bit was missing var making it global which was causing this... Sorry to anyone who's time I wasted!

Upvotes: 0

Related Questions