组成结构的Yjs事务性修改

时间:2018-07-04 21:03:48

标签: javascript

此帖子应带有标签 y-js (这是一个JavaScript框架),但我没有足够的声誉来创建它。

使用组合的共享数据结构(即Y.MapY.ArrayY.Text的结构),如何在不完成之前Yjs发送事件的情况下初始化这样的结构初始化?

示例用例:

y.db.startTransaction(someId) // what to use instead?

// create a new person
y.share.persons.push([Y.Map])
var person = y.share.persons.get(y.share.persons.toArray().length - 1)
person.set('name', Y.Text)
person.get('name').insert(0, 'John Doe')
person.set('age', 45)

y.db.finishTransaction(someId) // what to use instead?

我的问题是,在观察添加的新人时,我希望它的格式正确且完整,但是在使用y.share.persons.observe(…)时我观察到的是不完整的人。

以下代码片段显示了我的实际问题。其输出是:

age on observation: undefined
age after setTimeout: 45

Y({
  db: {name: 'memory'},
  connector: {
    name: 'websockets-client',
    room: 'so_transactions'
    // uses default url for demonstration purpose
  },
  share: {'persons': 'Array'}
}).then(y => {
  // I want to observe when new persons are added.
  // I expect them to have a defined 'name' and 'age'.
  y.share.persons.observe(({type, values}) => {
    // my problem: the age is not set yet.
    console.log('age on observation: '+values[0].get('age'))
    // deferred works:
    setTimeout(() => console.log('age after setTimeout: '+values[0].get('age')))
  })

  // I want to create a new person
  y.share.persons.push([Y.Map])
  var person = y.share.persons.get(y.share.persons.toArray().length - 1)
  person.set('name', Y.Text)
  person.get('name').insert(0, 'John Doe')
  person.set('age', 45)
})
<script src="https://cdn.jsdelivr.net/npm/yjs@12/dist/y.js"></script>
<script src="https://cdn.jsdelivr.net/npm/y-array@10/dist/y-array.js"></script>
<script src="https://cdn.jsdelivr.net/npm/y-websockets-client@8/dist/y-websockets-client.js"></script>
<script src="https://cdn.jsdelivr.net/npm/y-memory@8/dist/y-memory.js"></script>
<script src="https://cdn.jsdelivr.net/npm/y-map@10/dist/y-map.js"></script>
<script src="https://cdn.jsdelivr.net/npm/y-array@10/dist/y-array.js"></script>
<script src="https://cdn.jsdelivr.net/npm/y-text@9/dist/y-text.js"></script>

0 个答案:

没有答案