diff --git a/src-docs/spec/sendUpdate.md b/src-docs/spec/sendUpdate.md index 147ed5b..1e50b50 100644 --- a/src-docs/spec/sendUpdate.md +++ b/src-docs/spec/sendUpdate.md @@ -29,6 +29,21 @@ Send an update to all peers. - `descr`: short, human-readable description what this update is about. this is shown e.g. as a fallback text in an e-mail program. +Example: + +```js +window.webxdc.sendUpdate( + { payload: "Hello from Alice" }, + "A 'hello' message" +); + +// Peers can receive messages as such: +window.webxdc.setUpdateListener((update) => { + console.log(update.payload); +}); +// 'Hello from Alice' is printed in the console +``` + All peers, including the sending one, will receive the update by the callback given to [`setUpdateListener()`](./setUpdateListener.html). diff --git a/src-docs/spec/setUpdateListener.md b/src-docs/spec/setUpdateListener.md index ff5a063..2d44db1 100644 --- a/src-docs/spec/setUpdateListener.md +++ b/src-docs/spec/setUpdateListener.md @@ -29,6 +29,40 @@ Each `update` which is passed to the callback comes with the following propertie - `update.summary`: optional, short text, shown beside icon (see [`sendUpdate()`]) +Example: + +```js +let myDocumentState = ""; +const initialPendingUpdatesHandledPromise = window.webxdc.setUpdateListener( + (update) => { + // Remember that the listener is invoked for + // your own `window.webxdc.sendUpdate()` calls as well! + + // Dummy document update logic. + // Yours might be more complex, + // such as applying a chess move to the board. + myDocumentState = myDocumentUpdate; + + const areAllUpdatesProcessed = update.serial === update.max_serial; + if (areAllUpdatesProcessed) { + renderDocument(); + } + } +); + +initialPendingUpdatesHandledPromise.then(() => { + renderDocument(); +}); + +// Let's only call this when there are no pending updates. +function renderDocument() { + document.body.innerText = myDocumentState; +} + +// Peers can send messages like this +window.webxdc.sendUpdate({ payload: "Knight d3" }, "Bob made a move!"); +``` + Calling `setUpdateListener()` multiple times is undefined behavior: in current implementations only the last invocation works. [`sendUpdate()`]: ./sendUpdate.html