0

What I am doing:

I am retrieving list items from list using javascript as per visual webpart custom property. I have created a dropdown in webpart editor part from where I am getting site url. As per site url, I am retrieving list items from that perticular site.

My Problem:

My problem is that when I am adding same webpart multiple times on single page then all my javascript functions and variables are conflicting. So, that only one webpart is working and other is not.

Example:

Page1.aspx

Webpart1

<script type="text/javascript">
    var x,y;
    function temp(siteurl){
    var ctx,web;
    var a,b,c,d;
    x =  siteurl;
    getweb();
    if(siteurl == 'xyz'){
      a = a+b;
    }
    else{
      a = c+d;
    }
    alert("Items of site:"+siteurl);
    //append list items to div with classname 'myclass'
    }
    function getweb(){
    alert(x);
    }
</script>
<div class='myClass'>
</div>
<script type="text/javascript">
   $(document).ready(function () {
      SP.SOD.executeFunc('sp.js', 'SP.ClientContext', temp);
   });  
</script>

Webpart1 ( add same webpart on page again with different property[siteurl value] )

// same as above
<script type="text/javascript">
    var x,y;
    function temp(siteurl){
    var ctx,web;
    var a,b,c,d;
    x =  siteurl;
    getweb();
    if(siteurl == 'xyz'){
      a = a+b;
    }
    else{
      a = c+d;
    }
    alert("Items of site:"+siteurl);
    //append list items to div with classname 'myclass'
    }
    function getweb(){
    alert(x);
    }
</script>
<div class='myClass'>
</div>
<script type="text/javascript">
   $(document).ready(function () {
      SP.SOD.executeFunc('sp.js', 'SP.ClientContext', temp);
   });  
</script>

I am executiong query with context.executeQueryAsync(success,failed).

Any Solution ?

5
  • 2
    This is a JavaScript scoping problem, you are creating global variables and assigning them values which are then read by any other web parts/script that might be referencing the same variables. Commented Aug 31, 2015 at 12:18
  • There are some variables in my code which are useful in multiple function, that's why I have declared a global variables. Any other way to access variables in all functions & not conflicting in other webpart zone ?? Commented Aug 31, 2015 at 12:32
  • Unset the values of all variables at the end of the script. stackoverflow.com/questions/1596782/…
    – Akhoy
    Commented Aug 31, 2015 at 12:39
  • @Akhoy, I have reset the all variable before calling my main function. Commented Aug 31, 2015 at 12:52
  • Indeed.. JS scoping.. smashingmagazine.com/2009/08/… Commented Aug 31, 2015 at 14:31

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.