Skip to content
This repository was archived by the owner on Sep 8, 2025. It is now read-only.

Commit b99aa21

Browse files
committed
Update README.md
1 parent 96c7b9e commit b99aa21

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

README.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ Simple undo manager to provide undo and redo actions in JavaScript applications.
66
- [Demos](#demos)
77
- [Installation](#installation)
88
- [Example](#example)
9+
- [Updating the UI](#updating-the-ui)
910
- [Methods](#methods)
1011
- [add](#add)
1112
- [undo](#undo)
@@ -23,6 +24,7 @@ Simple undo manager to provide undo and redo actions in JavaScript applications.
2324

2425
## Demos
2526

27+
* [CodeSandbox with RGB color slider](https://codesandbox.io/s/undo-manager-color-sliders-z4myoj)
2628
* [Undo Manager with canvas drawing](https://arthurclemens.github.io/JavaScript-Undo-Manager/)
2729
* [JSBin demo, also with canvas](http://jsbin.com/tidibi/edit?js,output)
2830

@@ -90,6 +92,66 @@ undoManager.redo();
9092
console.log(people); // logs: {101: "John"}
9193
```
9294

95+
## Updating the UI
96+
97+
TL;DR UI that relies on undo manager state - for example `hasUndo` and `hasRedo` - needs to be updated using the callback function provided with `setCallback`. This ensures that all internal state has been resolved before the UI is repainted.
98+
99+
Let's say we have an update function that conditionally disables the undo and redo buttons:
100+
101+
```js
102+
function updateUI() {
103+
btn_undo.disabled = !undoManager.hasUndo();
104+
btn_redo.disabled = !undoManager.hasRedo();
105+
}
106+
```
107+
108+
You might be inclined to call the update in the undo/redo command pair:
109+
110+
```js
111+
// wrong approach, don't copy
112+
const undoManager = new UndoManager();
113+
const states = [];
114+
115+
function updateState(newState) {
116+
states.push(newState);
117+
updateUI();
118+
119+
undoManager.add({
120+
undo: function () {
121+
states.pop();
122+
updateUI(); // <= this will lead to inconsistent UI state
123+
},
124+
redo: function () {
125+
states.push(newState);
126+
updateUI(); // <= this will lead to inconsistent UI state
127+
}
128+
});
129+
}
130+
```
131+
132+
Instead, pass the update function to `setCallback`:
133+
134+
```js
135+
// recommended approach
136+
const undoManager = new UndoManager();
137+
undoManager.setCallback(updateUI);
138+
139+
const states = [];
140+
141+
function updateState(newState) {
142+
states.push(newState);
143+
updateUI();
144+
145+
undoManager.add({
146+
undo: function () {
147+
states.pop();
148+
},
149+
redo: function () {
150+
states.push(newState);
151+
}
152+
});
153+
}
154+
```
93155

94156
## Methods
95157

0 commit comments

Comments
 (0)