Two way binding is not work

I want to achieve two-way synchronization between two documents, but there is a special point here, that is, I need to initialize the document in advance, and hope that the broadcast will not be triggered during the initialization process, so I put the initialization logic in front, but after the front Unable to synchronize data

const doc1 = new Y.Doc()
const doc2 = new Y.Doc()
const syncUpdate = Symbol('sync-update')

doc1.transact(() => {
  doc1.getMap('root').set('aa', 1)
doc2.transact(() => {
  doc2.getMap('root').set('aa', 1)

doc1.on('update', (update, origin) => {
  if (origin === syncUpdate) return
  Y.applyUpdate(doc2, update, syncUpdate)

doc2.on('update', (update, origin) => {
  if (origin === syncUpdate) return
  Y.applyUpdate(doc1, update, syncUpdate)

doc1.getMap('root').set('aa', 123)
console.log(doc2.getMap('root').get('aa'), 'init') // can not print 123

The recommended approach is to have the client (or server) who creates the Doc populate it with initial data. All other clients should sync before editing.

Full discussion: Initial offline value of a shared document

As far as I know it’s not possible to selectively apply or broadcast some updates and not others. As soon as you skip an update, that Doc has a “hole” in it. No other updates will work as YJS will wait for the missing update, ensuring that updates are not applied out-of-order.

1 Like