Gabriel Linassi
Gabriel Linassi

Reputation: 541

best way to share objects between js files

I want to share this object between several files so they will be able to read and modify it.

obj = {id: 34234, name: 'xxxx', surname: 'yyyy'};

Should I import my js file into all my html files like so

html1.html <script src='myObj.js'></script>
html2.html <script src='myObj.js'></script>
html3.html <script src='myObj.js'></script>
...

or use localstorage.setItem() / localstorage.getItem() ? Which is the best approach?

Obs: If context interests you, it's about calling a API that returns users/projetcs/project-steps... When user logs in, I want to fetch all theirs projects. If user edit it, loads the project obj by its id and alter it and then send the change to the server. Same happen to other things like project-steps (but this is loaded into another page).

Upvotes: 1

Views: 851

Answers (1)

Abdelrahman Gobarah
Abdelrahman Gobarah

Reputation: 1589

You have to call this file, before any another files, if you use ajax be sure to call another functions in the SUCCESS CALLBACK of ajax request

var commonModule = (function() {
  'use strict';
  
  var userInfo = { id: 1, name: 'go' }; // use ajax to set it if you want

  return {
    userInfo: userInfo
  };
})();

//in another file you can call 

console.log(commonModule.userInfo.name);

Upvotes: 3

Related Questions