Skip to content

Commit f74bfee

Browse files
committed
feat(refs): unbind nested refs when parent is unbound
1 parent 13a1f8c commit f74bfee

File tree

2 files changed

+40
-6
lines changed

2 files changed

+40
-6
lines changed

src/index.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ function subscribeToDocument ({ ref, obj, key, depth, resolve }) {
7575
// TODO max depth param, default to 1?
7676
if (depth > 3) throw new Error('more than 5 nested refs')
7777
const subs = Object.create(null)
78-
return ref.onSnapshot(doc => {
78+
const unbind = ref.onSnapshot(doc => {
7979
if (doc.exists) {
8080
updateDataFromDocumentSnapshot({
8181
snapshot: createSnapshot(doc),
@@ -90,6 +90,14 @@ function subscribeToDocument ({ ref, obj, key, depth, resolve }) {
9090
resolve()
9191
}
9292
})
93+
94+
return () => {
95+
unbind()
96+
for (const subKey in subs) {
97+
const sub = subs[subKey]
98+
sub.unbind()
99+
}
100+
}
93101
}
94102

95103
function bindDocument ({

test/refs.spec.js

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,7 @@ beforeEach(async () => {
1919
await d.update({ ref: c })
2020

2121
vm = new Vue({
22-
render (h) {
23-
return h('ul', this.items && this.items.map(
24-
item => h('li', [item])
25-
))
26-
},
22+
render: h => h(),
2723
data: () => ({
2824
a: null,
2925
b: null,
@@ -186,3 +182,33 @@ test('unbinds all refs when the document is unbound', async () => {
186182
cSpy.mockRestore()
187183
dSpy.mockRestore()
188184
})
185+
186+
test('unbinds nested refs when the document is unbound', async () => {
187+
const c = collection.doc()
188+
const d = collection.doc()
189+
const aSpy = spyUnbind(a)
190+
const cSpy = spyUnbind(c)
191+
const dSpy = spyUnbind(d)
192+
193+
await a.update({ a: true })
194+
await c.update({ ref: a })
195+
await d.update({ ref: c })
196+
197+
await vm.$bind('d', d)
198+
expect(vm.d).toEqual({
199+
ref: {
200+
ref: {
201+
a: true
202+
}
203+
}
204+
})
205+
vm.$unbind('d')
206+
207+
expect(dSpy.mock.calls.length).toBe(1)
208+
expect(cSpy.mock.calls.length).toBe(1)
209+
expect(aSpy.mock.calls.length).toBe(1)
210+
211+
aSpy.mockRestore()
212+
cSpy.mockRestore()
213+
dSpy.mockRestore()
214+
})

0 commit comments

Comments
 (0)