Global state is conventionally frowned upon. However, I think I can use it clientside to make my app simpler.
I have an AJAX web app that sets up several values when the user logs in - user id, as well as som开发者_JAVA技巧e other information. This info does not change for the lifetime of the app.
I also have a cache of data to minimize trips to the server.
Can I safely make all these global? (the read-only user info and the cache) I think it would make it simpler because then I wouldn't have to worry about passing the values off between functions in sometimes awkward ways.
Essentially, it'd be like constants whose values aren't known at "compile-time."
In some ways, the DOM itself serves as a form of global state - I could store a value in HTML and it would be accessible from anywhere in the program.
There's nothing wrong in using globals, if you know what you're doing. Try to keep it clean by wrapping all your "constants" in a single global object. The major concern with globals is that you're tied to a single instance of whatever state your globals store, which may or may not be a problem in your case.
You could create a namespace, this way variables would be like global, but you wouldn't have to worry too much for clashes and that kind of stuff. Facebook does that on some of it's APIs.
Just to be safe, here's an example safe namespace implementation:
if(!window.MY_NAMESPACE){
MY_NAMESPACE = {
a_variable : "some value",
a_function: function(params){
return a_variable;
},
};
}
That way you get something like global stuff, without clashing with other variables in the document (or duplicates of your script)
I think it is perfectly OK to use global state for the purposes you mentioned. Just make sure they are written to only once, i.e. not changed during execution. So try to give them names that you won't accidentally overwrite them afterwards (which is always a danger in Javascript - forgeting var
and your variable becomes global, i.e. attached to the window
object) and preferably put them all into the same structure, to further minimize the danger of name collisions (less names, less collisions).
Also keep in mind, that the variables are not really 'global'; if the user keeps logged in but opens a new window to your site, the 'global' variables are gone. In this case you have to ensure, that there won't be an inconsistency, i.e. the server assumes that given a user is logged in, the variables are set.
精彩评论