Is This a Global Versus Local Variable Problem?

I intend to use a variable (myselector) with a text value (e.g. roses, Big Sur, Pacific Grove, night, etc.) for the sort criteria of my photography list.  Selection of a tab from a Tabbed Panel will appropriately define the variable and the selected thumbnails will display in the Content Panel.
The variable "myselector" is defined in the head section; a function for each tab of the Tabbed Panel will redefine the variable per the selected tab.  Within the function, I am not using "var" to call the variable.  Though the variable "myselector" should be global, the changes to its value are discarded when the function closes.  This indicates that it is functioning like a local variable in the function.  After a bit of reading, I've not found the cause of the global/local discrepancy or a fix for it.
Diagnosis History - I generated a simplified code.  Variable "myselector" is defined as "abcd"; function "myfilter" is called by onclick of the text "button" and changes "myselector" to "efgh".  At the end of the file, I used "document.write (myselector) to output the "myselector" value.  The script follows.
The end value of "myselector" does not change.  However, when I add "document.write (myselector)" to the function, then the changed value is displayed.
I ask someone to explain what I am doing incorrectly or, at least, guide me to a solution.  I thank you for your assistance.
Scott
<script type="text/javascript">
var myselector="abcd";
function MM_callJS(jsStr) { //v2.0
  return eval(jsStr)
</script>
</head>
<body>
<div id=text>
<p onclick="MM_callJS('myfilter();')">Button</p>
<script type="text/javascript">
function myfilter() {myselector="efgh"; }
</script>
<script type="text/javascript">
document.write (myselector);
</script>
</div>

Dear Ben:
I thank youfor your patience.  This includes the script using Insert - Syntax Highlighting - Java.
The coding needs a lot of clean up but I want it to work, first.
Scott
<script src="SpryAssets/xpath.js" type="text/javascript"></script>
<script src="SpryAssets/SpryData.js" type="text/javascript"></script>
<script src="SpryAssets/SpryTabbedPanels.js" type="text/javascript"></script>
<script type="text/javascript">
var dsphotodata = new Spry.Data.XMLDataSet("EM_photo.xml", "/gallery");
</script>
<script  type = "text/javascript">
function MM_callJS(jsStr) { //v2.0
  return eval(jsStr)
</script>
<script type="text/javascript">
var dsphoto = new Spry.Data.XMLDataSet("EM_photo.xml", "/gallery/photos/photo");
dsphoto.filter(subjectfilter);
var myselector;
</script>
<link href="SpryAssets/SpryTabbedPanels.css" rel="stylesheet" type="text/css" />
</head>
<body>
This is a test of Scott's efforts to program his website.
<br />
<br />
<div id="TabbedPanels1" class="TabbedPanels">
  <ul class="TabbedPanelsTabGroup">
    <li class="TabbedPanelsTab" tabindex="0" onclick="MM_callJS('{myselector=\'animal\'}; subjectfilter(); dsphoto.filter(subjectfilter); ')">Tab 1</li>
    <li class="TabbedPanelsTab" tabindex="0" onfocus="MM_callJS('myselector=\&quot;pgbeach\&quot; subjectfilter(); dsphoto.filter(subjectfilter); ')">Tab 2</li>
    <li class="TabbedPanelsTab" tabindex="0">Blank</li>
</ul>
  <div class="TabbedPanelsContentGroup">
    <div class="TabbedPanelsContent" >Content 1
      <br />
<br />
<script> {document.write (myselector)} </script>
      <br />
      <div spry:region="dsphoto dsphotodata"> <img src="{dsphotodata::thumbnail/@base}{@thumbpath}" width = {@thumbwidth}px height = {@thumbheight}px spry:repeat="dsphoto" onclick="dsphoto.setCurrentRow('{ds_RowID}');" /></div>
    </div>
    <div class="TabbedPanelsContent">Content 2
      <script> {document.write (myselector)} </script>
      <br />
      <div spry:region="dsphoto dsphotodata"> <img src="{dsphotodata::thumbnail/@base}{@thumbpath}" width = {@thumbwidth}px height = {@thumbheight}px spry:repeat="dsphoto" onclick="dsphoto.setCurrentRow('{ds_RowID}');" /></div>
    </div>
    <div class="TabbedPanelsContent">Content 3  <script> {document.write (myselector)} </script><br />
<div spry:region="dsphoto dsphotodata"> <img src="{dsphotodata::thumbnail/@base}{@thumbpath}" width = {@thumbwidth}px height = {@thumbheight}px spry:repeat="dsphoto" onclick="dsphoto.setCurrentRow('{ds_RowID}');" /></div>
</div>
</div>
</div>
<div id="Selected_Photo" spry:detailregion = "dsphoto dsphotodata"  >
<img src="Photo-Thumbnails/{@thumbpath}" width = {@thumbwidth}px height = {@thumbheight}px /><br />
<img src="Photo-Email/{@path}" width = {@width}px height = {@height}px />
</div>
<script type="text/javascript">
var subjectfilter = function(dataSet, row, rowNumber, criteria) { if (row["@subject"].search (myselector) != -1) return row; return null; };
<!--
var TabbedPanels1 = new Spry.Widget.TabbedPanels("TabbedPanels1", {defaultTab:2});
//-->
</script>

Similar Messages

  • Global and Local Variable

    Hi Gurus, I was unable to see where I can define local and global variables? I see that help.sap.com documentation but where do I create. All variables that I create, are global because, they are visible to all and they all can use it? Any help would be greatly appreciated.

    As far as I know, Variables are re-usable objects that are not dependent upon InfoProvider. When I look at this link
    http://help.sap.com/saphelp_nw04/helpdata/en/5c/8db07d555411d189660000e829fbbd/frameset.htm
    it talks about Global and Local variable? Is this different than what we use in Query Designer?

  • Local variable problem

    I am making an application that takes an apartment number and number of occupants in that apartment and then displays a number of statistics. So far I haven't had much problem
    except on a what is probably a very simple problem.
    I have two buttons, and when "store" is clicked the info in the textboxes is input to an array.
    My problem is with the next button, "quit", this is where all the info is supposed to be displayed.
    All my variables that I need from "store" are local and are recognized in " the if statement in quit. Ive tried declaring them outside of the if statement, but it hasn't been working.
    {code}
    public void actionPerformed(ActionEvent event)
                   Object source = event.getSource();
                   Apartment input;
                   if (source == store)
                        Integer aptNo = Integer.parseInt(input1.getText());
                        Integer occup = Integer.parseInt(input2.getText());
                        input = new Apartment(aptNo, occup);
                        if(aptNo > BUILDING_SIZE)
                             JOptionPane.showMessageDialog(null, "That apartment number doesn't exist.");
                        else if(occup > MAX_OCCUPANTS)
                             JOptionPane.showMessageDialog(null, "Too many occupants, only 20 are permitted per apartment.");
                        else
                             occupants[aptNo] = occup;
                             input1.setText("");
                             input2.setText("");
                             JOptionPane.showMessageDialog(null, input.getNumber(occupants));
                   if (source == quit)
                   // I need the variables aptNo and occup in here to put into my methods for output, but I don't know how to get them.     
    {code}

    EmmCeeVee wrote:
    Thank you for all of the responses, it really helps me out.
    Obviously my knowledge of local variables is hurting as I switched it around as your said and declared the aptNo and occup outside of the if's.
    All I need is for the quit button to look at the array ( which has just been modified by the sotre button) and output a bunch of results.
    Heres where im at:Your problem is of scope of the variables.
    Here whatever variable you defined in actionPerformed they are local for that method (they are out of scope when the method is finished/called again), Upon this, the actionPerformed is called twice one for store and another time for quit. So you cant expect the value stored at store should be there still when you all quit
    If you want those values available on both the actions then make them a class level variables.
    Below is a sample program, might help you.
    class Employee
         String empName = null;
         int empNo;
         Employee(String eName,int eNmbr)
              this.empName = eName;
              this.empNo = eNmbr;
    class CheckVariableScope
            Employee empOb; // Here
         int eNo;
         String eName = null;
         public void checkScope(String action)
                    //Instead of defining Employee reference variable, eNo and eName  in checkScope method, define it @ class level.
                    // in your case they are Apartment input, Integer aptNo and Integer occup
                     // like above i did.
                     // If i comment the class level variable and uncomment method variable, this program also give the same error.
              //Employee empOb;
              //int eNo;             
              //String eName = null;
              if (action.equals("Store") )
                        eNo = 10;
                        eName = "Bob";
                        empOb = new Employee(eName, eNo);
                        System.out.println("The eName is : "+empOb.empName+" , empNo is : "+empOb.empNo);
                   if (action.equals("quit"))
                        System.out.println(" eNO from Object is : "+empOb.empNo);
                        System.out.println(eNo); //Error: may not have been intitialized
         public static void main (String st[])
              CheckVariableScope ob = new CheckVariableScope();
              ob.checkScope("Store");
              ob.checkScope("quit");
    }

  • Shall I use global or local variables for my program?

    Hello,
    1) I am using 2 while loops in parallele. One 50 ms timed and the other one 1000 ms. The 50 ms one gets data from a sensor. I want to display that data every 1000ms in the 1000 ms loop. I have used global variables to do that. Should I better use local variables?
    2) This question deals with the VI I have attached
    a)  Shall I initialise the "  Quitter programme " global variable in the main VI aswell ? Or is what I have done enough?
    b)
    I want the sequence to continue ( finishes the last sequence and goes back to the first one without any delay if possible ) until the user presses Quit. I am concerned about the " wait until " icon of the exterior main while loop ( set to be 250 ms at the moment ). This time, 250 ms, is the time it takes between the end of the last sequence and the beginning of the first sequence? Is that right? Once u start the first sequence, the while loop doesn’t do anything until the end of the last sequence ( my 3 sequences can take several minutes ) ?
    Hope I am clear… lol
    Don’t hesitate to ask any questions if not clear enough
    thanks a lot,
    David
    Attachments:
    Example1.zip ‏28 KB

    Bonjour Marc.  You will definitely have a race condition because you are writing to the global in a parallel loop.  You could click the stop button in the quitter program, then before it is read in the main loop, the lower loop writes a false to it, and your click is lost.  Why do you want a separate quitter program?  You may have a good reason but it isn't clear here.  I would not use globals or locals for this, just put your stop button on the main vi.  You already have one, so why do you want another one in another vi?  If you must do it this way, eliminate both lower loops.  They are not necessary.  The global default is set to false, so when you run the vi, it is false.  The button mechanical action is set to latch when released, so after clicking it will turn true until the main vi reads it, then it will automatically turn false.  So you don't need the lower loops to keep writing false to it.  If you just eliminate both lower loops, it will work fine.  The only purpose I could see for the quitter vi is to have one button cause several vi's to stop.  Instead of doing it this way, put one stop button in your main vi, create a reference (right click - create - reference), and wire this reference into all subvi's that the main calls.  The subvi's must be changed to accept the reference and use it.  This would be a much better method to close all vi's with one button.
    You could also get rid of the sequence structure (it hides code and makes it more difficult to read).  Just put all your code side by side.  The error in/out wire will ensure that the execution order will be fixed, just like in your first sequence with the open file and write file functions.  Just wire the error out of the write vi to the second write vi, and then the error out of the second write vi to the close vi.  No sequence structure needed, and all your code is viewable on one screen.
    - tbob
    Inventor of the WORM Global

  • Problem using local variable in event loop

    I have a state machine from which I want to monitor various controls, including "Start" and "Stop" buttons.  Not every state needs to monitor the controls.  At present, most states run timed loops.  In the first state that reads the front panel, I have an Event structure (inside a While loop) that monitors the various controls' Change Value events.  For numeric controls, I update variables (in shift registers) as needed.  The "Start" button is used to end the While loop controlling the Event structure, allowing the State to exit to the next state.
    My problem comes in subsequent states that employ this same idea.  Here, I put a Local Variable bound to the Start button and use the same code, but it frequently happens that when I enter this particular state, I cannot "turn on" the control -- I push the button, but it stays off.  Curiously, if it was On when I enter, I can turn it off, but then I'm stuck not being able to turn it on.
    I mocked up a very simply routine that illustrates this.  There are two sequences (corresponding to the two states).  Both use an Event loop with a local variable bound to my Stop button (really this is an LED control with custom colors).  I've deliberately moved the "initialization" (the declaration of the control in the block diagram) out of the Event loops -- putting it inside the first loop modifies the behavior in another strange way.
    Here's my thinking on how I would expect this to work:  The code outside Event Loop 1 should have little effect.  Assume the Stop button is initially Off.  You will "sit" in Event Loop 1 until you push the Stop button, changing its value to True; this value will be passed out of the Event case and cause the first While loop to exit.  You now enter the second sequence.  As I understand the Exit tunnel, it defaults to "False", so I'd expect to stay in the second Event loop until I turn the Stop button from On to Off, which will pass out a False, and keep me in the While for one more button push.  However, this doesn't happen -- I immediately exit, as though the "True" value of the Stop local variable is being seen and recognized by the Event loop (even though it hasn't changed, at least not in the context of this second loop).
    An even more curious thing occurs if I start this routine with the Stop button turned on.  Now I start in my Event loop waiting for a change, but this time the change will be from On to Off, which won't cause an exit from the frame.  This will be reflected by having the While loop count increment.  We should now be in the state of the example above, i.e. in an Event loop waiting for the control to be pushed again, and turned On.  However, clicking the control has no effect -- I cannot get it to "turn on".
    Where am I going astray in my thinking?  What is it about this method of doing things that violates the Labview paradigm?  As far as I can tell, what I'm doing is "legal", and I don't see the flaw in my reasoning, above (of course not -- otherwise I'd have fixed it myself!).  Note that because I'm using local variables inside Event loops (and I'm doing this because there are two places in my code where I want to do such testing), the Stop control is not latching (as required).  Is there something that gets triggered/set when one reads a latched control?  Do I need to do this "manually" using my local variable?
    I'll try to attach the simple VI that illustrates this behavior.
    Bob Schor
    Attachments:
    Simple Stop Conundrum.vi ‏14 KB

    altenbach wrote:
    Ravens Fan wrote:
    NEVER have multiple event structures that share the same events. 
    Actually, that's OK.  NOT OK is having multiple event structures in the same sequence structure.
    See also: http://forums.ni.com/ni/board/message?board.id=170&message.id=278981#M278981
    That's interesting.  I had always thought I read more messages discouraging such a thing rather than saying it was okay.  Your link lead me to another thread with this message. http://forums.ni.com/ni/board/message?board.id=170&message.id=245793#M245793.  Now that thread was mainly concentrating on registered user events which would be a different, but related animal. 
    So if you have 2 event structures they each have their own event queue?  So if you have a common event, one structure pulls it off its event queue and it does not affect the other structure's event queue?  I guess the inherent problem with this particular VI was that the second event structure locked the front panel.  Since the code never got to that 2nd event structure because the  first loop never stopped because the change was from true to false.  After reading your post and the others, I did some experimentation and turned off the Lock front panel on the 2nd structure, and that prevented the lockup of the program.
    Overall, the example VI still shows problems with the architecture and I think your answer should put the original poster on the right track.  I think as a rule I would probably never put the same event in multiple structures, I feel there are better ways to communicate the same event between different parts of a program,  but I learned something by reading your reply and about how the event structures work in the background.  Thanks.

  • How to: Transform Activity: Read global/local variable, execute java code

    Could anyone please show me how to do that???

    could you please elaborate your usecase? yes you can read global variable using getVariableData( ) xpath function and pass them as an argument to the processXSLT ( ) xpath function.
    You can read the global or local variables inside java exec using, please refer samples/references/javaexec sample.

  • Reference to a local variable object returned by a method is alive?

    I have an instance method getEmployee().
    This method forms a local variable, Employee and returns it.
    public Employee getEmployee()
    Employee e = new Employee();
    e.setSNo(sNo+=);
    e.setMailBox();
    return e;
    There's another instance method in the same class that calls getEmployee() in this manner:-
    Employee newEmployee = getEmployee();
    newEmployee.printDetails();
    I want to know whether the employee returned by getEmployee() is still alive when we are doing newEmployee.printDetails().
    I am confused because in C, the lifetime of a local variable is limited only to the life time of the function. Once the function finishes, the local variable is considered garbage.
    How does it work in case of Java?

    No, It rarely has any use but can be used to unload things (from a cache for example). However I have never needed to do this. All I know is that finallizers can only be relied on to clear up memory. How or why you would do this is another question.
    The GC runs when memory is low (not any other resource). It calls finalizers when it clears up objects. Therefore the only thing you can reliably release in a finalizer is memory. Other resources can become depleted without heap being depleated so you can't use finalizers to relialy clean up non-memory resources.
    Anyway.
    some more info on escape analysis
    a compile time escape analysis
    http://www.excelsior-usa.com/pdf/StackAlloc.pdf
    This can handle some finalizers
    This does not handle finalizers (marks them all as GLOBAL_ESCAPE
    http://delivery.acm.org/10.1145/330000/320386/p1-choi.pdf?key1=320386&key2=0718563811&coll=Portal&dl=ACM&CFID=15151515&CFTOKEN=6184618
    bit more recent and about runtime optimization (finalizers not handled)
    http://ssw.jku.at/Research/Papers/Ko05/Ko05.pdf
    I don't think that not handling finalizers is too much of a problem. Most objects that will benifit from stackability are small objects anyway (especially the built in wrapper types). Most objects that have custom finalizers tend to be pretty complicated.
    matfud

  • Control buttons in local variables

    hi,
    i have been trying to do this for a long time. i just never learned how to make it work. can someone please guide me?
    i have this program with many many local variables and i know that this forum absolutely hate LOCAL VARIABLES.
    I want to program this the right way, so can you guys please help take a look at my code and see what i can do in order to REMOVE local variables if possible?
    Best regards,
    Krispiekream
    Attachments:
    test.vi ‏768 KB

    does this work?
    i split up the zip file to 2.88mb each.
    i think there is a file size limit of 5mb
    can you rename test01.zip to test.z01
    can you rename test02.zip to test.z02
    Best regards,
    Krispiekream
    Attachments:
    test.zip ‏1078 KB
    test01.zip ‏2847 KB
    test02.zip ‏2847 KB

  • Create Type NI_MultipleNumericLimitTest for local variable

    I am using  Multiple numeric test in my seq &  documenting in case of   Seq fail
    i.e when the  value is not in the limits
    I am using for-each-loop step type for this
    I want  a Local variable  of type  NI_MultipleNumericLimitTest      in my foreach (current element ) 
    but am not able to generate   a local of tht type!!
    what   measures to take to do so

    You cannot create a variable of a step type.  Step types can only be used to create steps.
    What is your goal?  Maybe there is a better way to accomplish what you want.
    If you are looking to dynamically change the limit set you need to use other types like NI_LimitMeasurmeent or an array of those.
    Regards,
    jigg
    CTA, CLA
    teststandhelp.com
    ~Will work for kudos and/or BBQ~

  • While local variable initialized inside try block compiler throws error???

    Check out this code where two local variables(one String and the other int type) is declared at the beginning of the method and initialized inside try block. now when i compile this app, it gives an error sayin' that Variables not been initialized. Can anyone tell me why compiler is throwin' an error message?
    Many thanks.
    import java.io.*;
    public class Test{
    public static void main(String[] args){
    String aa;
    int c;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("EnterAnything:");
    try{
    aa = in.readLine();
    c = 1;
    catch(IOException e){
    System.out.println(e.getMessage());
    System.out.println(aa);
    System.out.println(c);
    }

    jfbriere,
    Thanks to u all.
    that every reference to the variable is necessarily preceded
    by execution of an assignment
    to the variable.But I've initialized the variable c and aa inside try block before referencing it as a parameter of println()?
    Can u clarify this?
    --DM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Local variable hides a field

    hi everyone ,
    i am creating a button but it will show that local variable hides a field . this not an error or warning
    JRadioButton a1Btn = new JRadioButton("Physical connectivity");
           a1Btn.addActionListener(this) ;here a1Btn shows local variable hides a field.

    Correct, it is not an error to have a local variable with the same name as a field of the class.
    IDE's such as Eclipse often have options that will flag such name shadowing as a warning, so you'll know when you accidentally do this.
    But note that you can always access the class's field by prepending "this.", for example, "this.a1Btn".

  • Error in local variable

    1 am writing this query in oracle 11g in which i have declared a local variable v_SETRESULT which will
    store maximum +1 value of VISIT_ID which is my column in table VISIT and this column
    data type is integer
    my query
    declare
    v_SETRESULT NUMBER;-----------this is declaration of local variable
    begin
    SELECT Coalesce(Max(VISIT_ID), 0)+1
    INTO v_SETRESULT
    FROM Visit--------this is my name of table;
    dbms_output.put_line(v_SETRESULT);
    end;
    when i run this gives me this error
    anonymous block completed
    what does it mean

    yes iam doing this SQL Developer iam new to oracle 11g but i have previously worked in SQL Server 2005
    and if you run this query in SQL Server 2005 i get my result printed
    my query of SQL Server 2005
    Declare @v_SETRESULT as int
    begin
    SELECT @v_SETRESULT=Coalesce(Max(VISIT_ID), 0)+1
    FROM Visit;
    --dbms_output.put_line(v_SETRESULT);
    print @v_SETRESULT
    end;
    but when i run that above query which i posted previously this gives me this message
    rather than printing the result
    anonymous block completed
    then how to see my result printed

  • Local Variables Versus Global Variables

    DATA A TYPE I VALUE 100.
    PERFORM PRINT_DATA.
    FORM PRINT_DATA.
               DATA A(10) TYPE C 'HELLO'.
               WRITE / A. "Wanted to Print 100 (Global)
               WRITE / A.  "Wanted to Print 'HELLO'(Local)
    ENDFORM.
    Note : Both the times, the Local Variable 'A' is Printed .
    ?Is there any way to   Differentiate the Local and Global Variables When the Names Are Same.*
    *It Might be Possible in Object Oriented But I am Looking for the Same in FORMs.

    Hello Gagan,
    You want to print the Global as well as the local values of the variable named "A". Here are a couple of approaches:
    1.The 'Subroutines' are part of the modularization techniques. There are certain keywords like "using" & "Changing" so that you can work by passing Values.
    2. There is a keyword named "LOCAL". Declare data object with the keyword "LOCAL" and then try the 'write" statement. I suppose this should work for you.
    Let me know if any one of the above works or if you need more help.
    Best Regards,
    Chaitanya

  • Global, local variables in SubVI's

    Hi,
    I'm having a problem with what is probably a 'feature' of labview
    (using ver 6.1).
    When running multiple SubVI's of the same type, any local variables
    declared within the SubVI are globally scoped across all instances of
    that SubVI within one VI. Is there any way to prevent this?
    I am trying to store the Status of the SubVI in a local, but obviously
    each instance of the SubVI ends up with the same status. Currently i
    have solved this by having exact copies of the SubVI for each
    instance, but obviuosly as far as labview is concerned they are now
    different SubVI's, i consider this a bit of a hack and would rather
    avoid it.
    Any pointers?
    Many Thanks,
    Ed

    If you make the sub-VI reentrant, you will get the type of local you're looking for. On the sub-VI's menus, goto File >> VI Properties >> Category >> Execution >> Reentrant Execution.

  • Convert local variable to global - labView

    I have a sequence with a VI that contains a local variable array. Now I need that data saved for use by a VI in a later sequence. Can locals be converted to globals or must it be re-created and all references to it changed?
    Thanks,
    jvh 

    Hi,
    If you are using the SequenceContext as the reference, then your lookup string to your variable would need to change.
    eg "Locals.MyArray" would become "StationGlobals.MyArray"
    Does this help
    Regards
    Ray Farmer
    Regards
    Ray Farmer

Maybe you are looking for