Search code examples
knockout.jsrequirejsoracle-jet

How to maintain global variables in KnockoutJs throughout the application?


I have a container page Index.html(this can be treated as a master page) in which I load different pages Home.html, people.html and each page is having its own viewmodel js file (Home.js, people.js). I navigate from Home.html to People.html. In Home.js I make an Ajax call and I need the data it fetches in People.js when I go to People.html page. I have tried using PublishOn and SubscribeTo but dint yield the results, I have tried creating a variable in main.js and thought of using it in both Home.js and people.js, I am able to access it by using $root. but I can do this only in Html page but not in Js. Hope I am clear with my problem statement. **Note:**I am using RequireJs as well for configuration.

Please help me on this.


Solution

  • If the data is truly global, one way is to create a new AMD/RequireJS module that you then identify as a dependency in the ViewModels for Home.html and People.html. You then let this shared module manage the data. I would be tempted to move the Ajax call from Home's ViewModel into this new shared module.

    Using $root creates an implicit contract between your views. Some would say this is hard to maintain and that it is better to document relationships through child view parameters. If the data is not global, but only shared between two child views of a specific view, then you can pass data to child views through parameters. Are you using Knockout components or Oracle JET modules? Both allow you to pass parameters from a parent View to a child ViewModel.