Skip to content

Commit 8256ecb

Browse files
committed
feat(bind): manual bind with $bind
1 parent d93915c commit 8256ecb

File tree

2 files changed

+68
-15
lines changed

2 files changed

+68
-15
lines changed

src/index.js

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ function bindDocument ({
4444

4545
const unbind = document.onSnapshot((doc) => {
4646
// TODO test doc.exist
47-
console.log('doc data', doc)
47+
// console.log('doc data', doc)
4848
const [data, refs] = extractRefs(createSnapshot(doc))
4949
vm[key] = data
5050
return
@@ -66,29 +66,41 @@ function bindDocument ({
6666
}
6767
}
6868

69+
function bind ({ vm, key, ref }) {
70+
if (ref.add) {
71+
bindCollection({
72+
vm,
73+
key,
74+
collection: ref,
75+
})
76+
} else {
77+
bindDocument({
78+
vm,
79+
key,
80+
document: ref,
81+
})
82+
}
83+
}
84+
6985
function install (Vue, options) {
7086
Vue.mixin({
7187
created () {
7288
const { firestore } = this.$options
7389
if (!firestore) return
7490
Object.keys(firestore).forEach(key => {
75-
const ref = firestore[key]
76-
if (ref.add) {
77-
bindCollection({
78-
vm: this,
79-
key,
80-
collection: ref,
81-
})
82-
} else {
83-
bindDocument({
84-
vm: this,
85-
key,
86-
document: ref,
87-
})
88-
}
91+
this.$bind(key, firestore[key])
8992
})
9093
}
9194
})
95+
96+
// TODO test if $bind exist and warns
97+
Vue.prototype.$bind = function (key, ref) {
98+
bind({
99+
vm: this,
100+
key,
101+
ref,
102+
})
103+
}
92104
}
93105

94106
export default install

test/bind.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import test from 'ava'
2+
import Vuefire from '../src'
3+
import {
4+
createSnapshot
5+
} from '../src/utils'
6+
import {
7+
db,
8+
tick,
9+
Vue
10+
} from './helpers'
11+
12+
Vue.use(Vuefire)
13+
14+
test.beforeEach(async t => {
15+
t.context.collection = db.collection()
16+
t.context.document = t.context.collection.doc()
17+
t.context.vm = new Vue({
18+
render (h) {
19+
return h('ul', this.items && this.items.map(
20+
item => h('li', [item])
21+
))
22+
},
23+
// purposely set items as null
24+
// but it's a good practice to set it to an empty array
25+
data: () => ({
26+
items: null,
27+
item: null,
28+
}),
29+
}).$mount()
30+
await tick()
31+
})
32+
33+
test('manually binds a collection', async t => {
34+
const vm = t.context.vm
35+
const collection = t.context.collection
36+
t.deepEqual(vm.items, null)
37+
await vm.$bind('items', collection)
38+
t.deepEqual(vm.items, [])
39+
await collection.add({ text: 'foo' })
40+
t.deepEqual(vm.items, [{ text: 'foo' }])
41+
})

0 commit comments

Comments
 (0)