user1298426
user1298426

Reputation: 3717

Variable declared at class level looses it's value while setting it in one method and retriving it from another method

Say I have a class with variable var1. I click on a button & it calls pageLoadMethod() which loads the page and inside it I set var1 to 10. Now I click on another button after page is loaded ajaxMethod() & try to retrive var1 value but not getting it's value set in pageLoadMethod() method.

    Class MyClass{

    def var1 = 1;

       def pageLoadMethod(){
         var1 = 10;
         ....
      }

       def ajaxMethod(){
         println var1; // prints 1 instead of 10
      }
   }

Upvotes: 0

Views: 65

Answers (2)

Kasper Ziemianek
Kasper Ziemianek

Reputation: 1345

I suppose MyClass is kind of controller. Whats the scope of this controller ? If You want to keep it's state between requests, you should use Session scope.

http://grails.org/doc/2.4.x/guide/single.html#controllersAndScopes

Upvotes: 1

lukelazarovic
lukelazarovic

Reputation: 1502

The premise of this answer is that MyClass is a controller, which I assume from the context.

In Grails the controller instances are by default created for each request - that's why you don't see changed value of var1 in the ajaxMethod.

You can make a singleton from the controller by adding this line into it:

static scope = "singleton"

After this you should see the changed value in ajaxMethod.

Another question is if this is a good approach when multiple users can access your controller at the same time - if you want to use the variable to save some state between user's requests, you should rather use session for that..

Upvotes: 1

Related Questions