Say I have a method that changes a value based on what the current value is. I will just make it very simple here:
changeValue(){
if(!this.value){
this.value = 'value1'
}
else if(this.value === 'value1'){
this.value = 'value2'
}
else if(this.value === 'value2'){
this.value = 'value3'
}
},
And then I have another method that changes to a fourth value if the current value is either 2 or 3
changeValues(){
if(this.value === 'value2' || this.value === 'value3'){
this.value = 'valueX'
}
},
Now I would like to add a click event that changes the value of valueX back to what it previously was, but I cannot specify it in the code, because the previous value could either be value2 or value3.
Is there a way to look at the variable "history", check what is previously was and then set it back to that?
changeBack(){
// if last value was value2 change back to value2
// if last value was value3 then change back to value3
}
You can use an array to keep track of the history of values.
Example:
class YourClass {
constructor() {
this.value = null;
this.valueHistory = [];
}
changeValue() {
if (!this.value) {
this.value = 'value1';
} else if (this.value === 'value1') {
this.value = 'value2';
} else if (this.value === 'value2') {
this.value = 'value3';
}
// Save the current value to history
this.valueHistory.push(this.value);
}
changeValues() {
if (this.value === 'value2' || this.value === 'value3') {
this.value = 'valueX';
}
}
changeBack() {
// Pop the last value from history and set it as the current value
if (this.valueHistory.length > 0) {
this.value = this.valueHistory.pop();
}
}
}
valueHistory
is an array that keeps track of the history of values. The changeBack method pops the last value from the history array and sets it as the current value.