-2

So I'm working a React/Typescript project, where I need to store a value for the number of rows that needs to be accessible globally.

Is it a good idea to define it on the window object?

window.MySpace = {};
MySpace.rowCount = 10;

Are there any issues that could arise as the project grows? Or is there a more elegant way of handling this through Typescript?

Thanks!

edit:

Declare it as a module in a module.ts file

export module Global {
    export const rowCount = 10;
}

Then import it to whichever file requires the value of rowCount.

blankface
  • 5,757
  • 19
  • 67
  • 114
  • 2
    Possible duplicate of [Storing a variable in the JavaScript 'window' object is a proper way to use that object?](https://stackoverflow.com/questions/12393303/storing-a-variable-in-the-javascript-window-object-is-a-proper-way-to-use-that) – Herohtar May 29 '19 at 04:03

2 Answers2

0

where I need to store a value for the number of rows that needs to be accessible globally

If you have to have to globally then ofcourse you would put it on window. The biggest concern would be naming MySpace conflict.

Rethink

However you probably don't need it globally, and really you should use a module.

basarat
  • 261,912
  • 58
  • 460
  • 511
0

When You need to store a value that needs to be accessible globally, create a global object with a unique name, with your variables as properties of that object:

window.MySpace= {};

Then use it in whatever way you prefer. Use it with functions

MySpace.show();
MySpace.hide();

Assign a value to it

MySpace.value=1;
MySpace.value=2;

different ways to handle that

MySpace.rowCount = 10;

and yes it is sometimes a good idea to define it on the window object, some cases require other ways of defining.

You're good to go!!

Akshay Mulgavkar
  • 1,727
  • 9
  • 22