Skip to content

Commit 0eff432

Browse files
committed
Add .once() to vjs doc
1 parent 185a95a commit 0eff432

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

src/index.js

+7
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,13 @@ function VDoc (options) {
3535
on: function (name, callback) {
3636
setIfUndefined(observers, name, set.create).add(callback)
3737
},
38+
once: function (name, callback) {
39+
const _f = (...args) => {
40+
this.off(name, _f)
41+
callback(...args) // eslint-disable-line node/no-callback-literal
42+
}
43+
this.on(name, _f)
44+
},
3845
off: function (name, callback) {
3946
const nameObservers = observers.get(name)
4047
if (nameObservers != null) {

src/index.test.js

+28-1
Original file line numberDiff line numberDiff line change
@@ -449,7 +449,7 @@ describe('events', () => {
449449
key2: { timestamp: 1500, data: 'dataB', clientId: 2 }
450450
})
451451

452-
// Event listener should've been called 3 times
452+
// Event listener should've been called 2 times
453453
expect(onUpdate.mock.calls).toEqual([
454454
[{ key1: { timestamp: 1000, data: 'dataA', clientId: 1 } }],
455455
[{ key1: { timestamp: 1100, data: null, clientId: 2 } }]
@@ -501,6 +501,33 @@ describe('events', () => {
501501
]
502502
])
503503
})
504+
505+
test('.once() should only be triggered once', () => {
506+
const doc = VDoc()
507+
const onUpdate = jest.fn()
508+
const onUpdateMultiple = jest.fn()
509+
510+
// Events after .on()
511+
doc.once('update', onUpdate)
512+
doc.on('update', onUpdateMultiple)
513+
514+
doc.set('key1', 'dataA', 1000, 1)
515+
doc.set('key1', 'dataA', 1000, 1)
516+
doc.set('key1', 'dataA', 1000, 1)
517+
doc.set('key1', 'dataA', 1000, 1)
518+
519+
expect(onUpdate.mock.calls).toEqual([
520+
[{ key1: { timestamp: 1000, data: 'dataA', clientId: 1 } }]
521+
])
522+
523+
// Verify that regular onUpdate is called for each one
524+
expect(onUpdateMultiple.mock.calls).toEqual([
525+
[{ key1: { timestamp: 1000, data: 'dataA', clientId: 1 } }],
526+
[{ key1: { timestamp: 1000, data: 'dataA', clientId: 1 } }],
527+
[{ key1: { timestamp: 1000, data: 'dataA', clientId: 1 } }],
528+
[{ key1: { timestamp: 1000, data: 'dataA', clientId: 1 } }]
529+
])
530+
})
504531
})
505532

506533
describe('subdocs', () => {

0 commit comments

Comments
 (0)