Reputation: 17003
I have an application that runs in various states, for example state1
, state2
, and state3
. Certain behavior of the application will depend on the state the application is in when e.g., a button is pressed, and state in turn will change based on button presses, etc.
I am wondering if there is a standard idiom or design pattern for keeping track of state changes in JavaScript. Perhaps my wording is misleading or inaccurate, so I will give an example. I might want to check state like this:
function foo() {
if (currentState === someState) {
doSomething();
}
}
But I would like to keep track of state in a way that I don't need to hardcode a string state in multiple places, i.e., I would like to avoid doing this:
function foo() {
if (currentState === 'state1') {
doSomething();
}
}
The first thing that came to mind is to create an appState
object that has a property for each possible state:
var appState = {
state1: 'state1',
state2: 'state2',
state3: 'state3'
}
This way I could change the current app state like:
currentState = appState.state1;
and check state like:
if (currentState === appState.state1) {
...
}
However, something feels off about this solution; perhaps the repetition of property name and value.
I don't have enough experience reading or writing JavaScript to know the common patterns and best practices yet. I am wondering if the situation I have described above has a standard solution/idiom that is followed by the JavaScript community. Through researching this question, I have come across the State design pattern, and this nice post on how to apply the pattern to JavaScript. I have considered going this route, and have not completely discounted it, but that strategy seems like it might be unnecessarily complex for a simple application.
Upvotes: 0
Views: 1690
Reputation: 138437
As javascript is quite dynamic, theres never a best solution. Its based on you what you like much or not. I would, to run a different function on an event, do sth like this:
var states={
dark:{
alert:function(){
alert("its night");
},
//more to come
},
bright:{
alert:function(){
alert("its day");
}
}
}//etc
Just put the functions in it, that change on every state, as you dont want to be repetetive. You could set a current state:
var currentstate=states.dark;
Now you can do, somewhere in your code:
currentstate.alert();
This will also work if state is set to bright. To check wich state is the current, you can do:
if(currentstate==states.dark)
But the states object isnt that senseless then in your example.
PS: To improve the upper structure, you could use OOP to have substates( that behave similar to another state)
states.grey=Object.create(states.dark);
states.grey.alert=function(){
alert("its getting brighter...");
};
Also this will solve your typo problem:
state.dak //error: cannot read property of undefined.
Upvotes: 2