Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
48
rated 0 times [  52] [ 4]  / answers: 1 / hits: 83897  / 9 Years ago, mon, november 23, 2015, 12:00:00

I've been working with little snippets of JavaScript during 3 years, but now I'm building a React application and I'm getting into it. There is a basic thing that I don't understand. React uses a Dispatcher and Stores to build its Flux pattern, the thing that I don't get is that this Dispatcher is visible in all the application, because Actions use the dispatcher to dispatch actions and Stores register to the Dispatcher to get notified (so it's not a new Dispatcher every time). So, how can I achieve this global scope or whatever it is called? How can achieve this using ES6 classes (modules)?



This question may be unclear due to my lack of experience programming real JavaScript, I hope that with the hep of community comments I'll be able to arrange that.


More From » reactjs

 Answers
17

You can always assign variables to window.MyClass = whatever (global.MyClass for nodejs) no matter where you are, and access these values from any other file in your application. That's not always the best way to go about sharing data globally in your application though. The module loader in nodejs (or AMD in ES6) takes whatever you export and caches it. Lets say you have a file like:



MyModule.js:



class MyClass {
constructor() {
this.someData = 55;
}
}

export default (new MyClass);


now whenever we require this file from elsewhere, we're ALWAYS being given the SAME instance of MyClass. This means:



file1.js:



import MyClass from './MyModule'
MyClass.someData = 100;


file2.js:



import MyClass from './MyModule'
console.log(MyClass.someData);


This is called the singleton pattern, where we pass around one common instance of your class all throughout your application. So in this manner we're able to access the same instance of MyClass from different files, all without polluting the global scope (we avoid making assignments to global.MyClass but accomplish the same functionality).


[#64300] Friday, November 20, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kinsleyashlynnh

Total Points: 64
Total Questions: 119
Total Answers: 98

Location: Burundi
Member since Sat, Aug 21, 2021
3 Years ago
;