React + Flux - How to avoid global variable
I have been working on React/Flux and am confused over the declaration of variable outside the component as in below code.
CounterComponent.js
var count;
function getCount (){
}
var CounterComponent = React.createClass({
getInitialState: function(){
return getCount();
},
render:function(){
}
})
module.exports = CounterComponent;
As in the above code, the doubt is that the variable count and function getCount seem to be global here. Is it okay to have variables and functions declared here, outside the component or need to placed inside. This looks like global pollution.
Also, if we consider a store, have seen very examples as below, here also, the variable CHANGE_EVENT seem to be global, is that okay.
CounterStore.js
var CHANGE_EVENT = 'change';
var MainStore = assign({},EventEmitter.prototype, {
AppDispatcher.register(function(payload){
var action = payload.action;
switch(action.actionType){
}
});
});
module.exports = MainStore;
I have searched for this answer, but couldnt get the right answer. From javascript perspective it looks like its polluting global, but what about in React?
Answer
It depends on the build system you use, if you use a system like browserify or webpack, then no variables would be global.
So if you do not use a bundler library, I suggest you to wrap your source code with a anonymous function, so that you wont pollute global namespace.
But I strongly suggest you to take a look with a modern approach using webpack which seems to be more popular within React and Flux community.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM