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.
Aucun commentaire:
Enregistrer un commentaire