Skip to content

Commit

Permalink
simplify setUpdateListener example
Browse files Browse the repository at this point in the history
  • Loading branch information
WofWca committed Jul 14, 2024
1 parent a394d7a commit 7263ac5
Showing 1 changed file with 7 additions and 22 deletions.
29 changes: 7 additions & 22 deletions src-docs/spec/setUpdateListener.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,43 +32,28 @@ Each `update` which is passed to the callback comes with the following propertie
Example:

```js
let myDocumentState = localStorage.getItem("myDocumentState") ?? "";

let initialPendingUpdatesHandled = false;
let myDocumentState = "";
const initialPendingUpdatesHandledPromise = window.webxdc.setUpdateListener(
(update) => {
// Remember that the listener is invoked for
// your own `window.webxdc.sendUpdate()` calls as well!

applyDocumentUpdate(update.payload);
localStorage.setItem("myDocumentState", myDocumentState);
localStorage.setItem("lastHandledUpdateSerial", update.serial);
// Dummy document update logic.
// Yours might be more complex,
// such as applying a chess move to the board.
myDocumentState = myDocumentUpdate;

const areMoreUpdatesPending = update.serial !== update.max_serial;
if (
!areMoreUpdatesPending &&
// We'll make the initial render when the promise resolves,
// because if there are no pending updates,
// the listener will not be invoked.
initialPendingUpdatesHandled
) {
if (!areMoreUpdatesPending) {
renderDocument();
}
},
parseInt(localStorage.getItem("lastHandledUpdateSerial") ?? "0")
}
);

initialPendingUpdatesHandledPromise.then(() => {
initialPendingUpdatesHandled = true;
renderDocument();
});

function applyDocumentUpdate(myDocumentUpdate) {
// Dummy `applyDocumentUpdate` logic.
// Yours might be more complex,
// such as applying a chess move to the board.
myDocumentState = myDocumentUpdate;
}
// Let's only call this when there are no pending updates.
function renderDocument() {
document.body.innerText = myDocumentState;
Expand Down

0 comments on commit 7263ac5

Please sign in to comment.