Yii2 comes with updated javasctipt module structure. Check it out read comments. You can use this approach for your own app.
Then I’ll tell you about 2 approaches how you could do that. The easiest one is just include what you need in your views.
$this->registerJs('myapp.post.isActive = true;', $this::POS_END); $this->registerJs('myapp.author.isActive = true;', $this::POS_END);
The advantage of such approach that you have full control on what do you include. But I’m pretty sure that in most cases you don’t need such level of control. Using convention over configuration principle you can adjust that for all you controller you’ll have specific module for all contoler’s action you have the function inside your module or another module like controller_action.js. Using this assertion you can easily add some helper for yii and initiate modules base on current route.
Finally for a change I will add one more example. Where I will initiate module base on data-attributes of body. I have rails project so you’ll have coffee script
### ### 'use strict' appRunner = exec: (controller, action = "init") -> ns = window.app if controller != "" && ns[controller] && typeof ns[controller][action] == "function" ns[controller][action]() init: () -> body = document.body controller = body.getAttribute( "data-controller" ) action = body.getAttribute( "data-action" ) appRunner.exec("common") appRunner.exec(controller) appRunner.exec(controller, action) window.app.common = init: () -> $(document).ready(()-> appRunner.init() )
As you can see here you have some common for your app logic and module with methods per your actions.
Resume: don’t mix js and PHP/Ruby/Whatever. Keep your code clean. Thanks.