Skip to content

Commit

Permalink
feat(refs): unbind nested refs when parent is unbound
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed Dec 13, 2017
1 parent 13a1f8c commit f74bfee
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 6 deletions.
10 changes: 9 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ function subscribeToDocument ({ ref, obj, key, depth, resolve }) {
// TODO max depth param, default to 1?
if (depth > 3) throw new Error('more than 5 nested refs')
const subs = Object.create(null)
return ref.onSnapshot(doc => {
const unbind = ref.onSnapshot(doc => {
if (doc.exists) {
updateDataFromDocumentSnapshot({
snapshot: createSnapshot(doc),
Expand All @@ -90,6 +90,14 @@ function subscribeToDocument ({ ref, obj, key, depth, resolve }) {
resolve()
}
})

return () => {
unbind()
for (const subKey in subs) {
const sub = subs[subKey]
sub.unbind()
}
}
}

function bindDocument ({
Expand Down
36 changes: 31 additions & 5 deletions test/refs.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,7 @@ beforeEach(async () => {
await d.update({ ref: c })

vm = new Vue({
render (h) {
return h('ul', this.items && this.items.map(
item => h('li', [item])
))
},
render: h => h(),
data: () => ({
a: null,
b: null,
Expand Down Expand Up @@ -186,3 +182,33 @@ test('unbinds all refs when the document is unbound', async () => {
cSpy.mockRestore()
dSpy.mockRestore()
})

test('unbinds nested refs when the document is unbound', async () => {
const c = collection.doc()
const d = collection.doc()
const aSpy = spyUnbind(a)
const cSpy = spyUnbind(c)
const dSpy = spyUnbind(d)

await a.update({ a: true })
await c.update({ ref: a })
await d.update({ ref: c })

await vm.$bind('d', d)
expect(vm.d).toEqual({
ref: {
ref: {
a: true
}
}
})
vm.$unbind('d')

expect(dSpy.mock.calls.length).toBe(1)
expect(cSpy.mock.calls.length).toBe(1)
expect(aSpy.mock.calls.length).toBe(1)

aSpy.mockRestore()
cSpy.mockRestore()
dSpy.mockRestore()
})

0 comments on commit f74bfee

Please sign in to comment.