我定義了一個充當堆棧的類,我可以將元素推送到它並撤銷/重做這些元素。Vanilla JS:如何跟蹤另一個對象的對象屬性?
export default class Stack {
constructor() {
this.history = [];
this.pointer = -1;
}
push(element) {
this.pointer += 1;
if (this.pointer < this.history.length) { this.history.length = this.pointer; }
this.history.push(element);
}
undo() {
if (this.pointer >= 0) {
// undo element...
this.pointer -= 1;
}
}
redo() {
if (this.pointer < this.history.length - 1) {
this.pointer += 1;
// redo element...
}
}
isEmpty() {
return this.history.length === 0;
}
canUndo() {
return !(this.isEmpty() || this.pointer === -1);
}
canRedo() {
return !(this.isEmpty() || this.pointer === this.history.lenght - 1);
}
...
然後我具有實例化對象Stack
並顯示按鈕使用undo
和redo
方法的另一對象;但我需要禁用它們時不能執行這些操作(我已經實現的方法canUndo
和Stack
canRedo
來驗證這一點)
我可以禁用按鈕時,我對它們進行初始化,但我不知道如何每次更改堆棧屬性時,是否可以撥打canUndo
和canRedo
方法,以便我可以禁用/啓用它們。對此最好的方法是什麼?
注意:按鈕在畫布中繪製,它們不是普通的HTML元素。我爲此使用ES6和無框架。