Private variable in null in component JS request

Hello,

I declared a private variable in my component class and it works good, when I get it in a method called in onRun().

But when I want to get the value in my JS request method it’s null.

Here’s my getter:

public function getSubjectsTexts() {
        return $this->subjectsTexts;
}

And here my on JS request method:

public function onGenerateDataSentences()
    {
        $subjectsTexts = $this->getSubjectsTexts();
        dd($subjectsTexts); // prints null
        
        // ...
 }

How can I get $subjectsTexts in onGenerateDataSentences()?

The data is just a huge array, which I placed in another file in plugin/acme/data/questionSubjects.php. I get it in onRun() like that:

$this->subjectsTexts = require_once(base_path('plugins/maki3000/goodbad/data/questionSubjects.php'));

I found a solution. I just require my array in the JS request method again:

public function onGenerateDataSentences()
{
       $subjectsTexts = require_once(base_path('plugins/maki3000/goodbad/data/questionSubjects.php'));
     
       // ...

}

I don’t know if that’s the way to go, but it works.

Something I saw in code of other plugin authors that I adapted is creating a “prepareVars” function, that prepares/initializes all the variables the component needs on every request, and call that in “onRun” and in every custom “onXY” action handler function. It’s a very useful pattern to avoid initializing the same variable at multiple points in the code.

2 Likes

To clarify here is the pattern mentioned by @marco.grueter

public function prepareVars()
{
    // Set common page variables
}

public function onDoSomething()
{
    $this->prepareVars();

    // Do thing
}

public function onAnotherThing()
{
    $this->prepareVars();

    // Do thing
}
2 Likes