P粉7647859242023-08-04 00:36:22
With the help of @Jared, I solved this problem.
I used localStorage to save the current state of the model and reload it when redirecting to another page.
const Model = (function () { let instance; let data = { isLogged: false, }; function init_localStorage() { save_localStorage(); } function load_localStorage() { let model = JSON.parse(localStorage.getItem('Model')); if (Object.keys(model).length === 0) { init_localStorage(); } data = model; } function save_localStorage() { localStorage.setItem('Model', JSON.stringify(data)); } function init() { load_localStorage(); return { getIsLogged: function () { return data.isLogged; }, setIsLogged: function (l) { data.isLogged = l; }, saveData: function () { save_localStorage(); } } } return { getInstance: function () { if (! instance) { instance = init(); } return instance; } } })();
Ultimately, I have two main functions: save... and load..., which read and save data from the localStorage object. As Jared said in the comments, JSON cannot stringify functions, so I created an object called data in which I store all the model's data (such as the isLogged variable).
Now, whenever I want to access the model's data, I first get its instance: let model = Model.getInstance(); Then I can access the method from the returned init function. When I request a Model instance, it first checks if the current instance is initialized. If not initialized, it calls the load_localStorage function to read data from localStorage and save it to the data variable.
Before redirecting to another page, I call the saveData function of the Model instance to save the data object to localStorage so that the redirected page can read the previously saved state.
In the HTML file, I included the js file like this: <script src="./../model/model.js"></script>.
I'm sure there are better solutions, maybe with more readable code, but this method works well enough for me :)