@@ -29,6 +29,56 @@ Each `update` which is passed to the callback comes with the following propertie
2929
3030- ` update.summary ` : optional, short text, shown beside icon (see [ ` sendUpdate() ` ] )
3131
32+ Example:
33+
34+ ``` js
35+ let myDocumentState = localStorage .getItem (" myDocumentState" ) ?? " " ;
36+
37+ let initialPendingUpdatesHandled = false ;
38+ const initialPendingUpdatesHandledPromise = window .webxdc .setUpdateListener (
39+ (update ) => {
40+ // Remember that the listener is invoked for
41+ // your own `window.webxdc.sendUpdate()` calls as well!
42+
43+ applyDocumentUpdate (update .payload );
44+ localStorage .setItem (" myDocumentState" , myDocumentState);
45+ localStorage .setItem (" lastHandledUpdateSerial" , update .serial );
46+
47+ const areMoreUpdatesPending = update .serial !== update .max_serial ;
48+ if (
49+ ! areMoreUpdatesPending &&
50+ // We'll make the initial render when the promise resolves,
51+ // because if there are no pending updates,
52+ // the listener will not be invoked.
53+ initialPendingUpdatesHandled
54+ ) {
55+ renderDocument ();
56+ }
57+ },
58+ parseInt (localStorage .getItem (" lastHandledUpdateSerial" ) ?? " 0" )
59+ );
60+
61+ initialPendingUpdatesHandledPromise .then (() => {
62+ initialPendingUpdatesHandled = true ;
63+ renderDocument ();
64+ });
65+
66+ function applyDocumentUpdate (myDocumentUpdate ) {
67+ // Dummy `applyDocumentUpdate` logic.
68+ // Yours might be more complex,
69+ // such as applying a chess move to the board.
70+ myDocumentState = myDocumentUpdate;
71+ };
72+ // Let's only call this when there are no pending updates.
73+ function renderDocument () {
74+ document .body .innerText = myDocumentState;
75+ };
76+
77+ // ...
78+ // Other peers, or you:
79+ window .webxdc .sendUpdate ({ payload: " Knight d3" }, " Bob made a move!" );
80+ ` ` `
81+
3282Calling ` setUpdateListener ()` multiple times is undefined behavior: in current implementations only the last invocation works.
3383
3484[` sendUpdate ()` ]: ./sendUpdate.html
0 commit comments