|
<template> |
|
<div id="app"> |
|
{{socketState}}<br/> |
|
<input v-on:keyup.enter='addPlayer($event)' placeholder="Add player" v-model='newPlayer' /> |
|
<div v-for='p in Object.values(playerList).sort( (a,b) => b.created - a.created)' :key='p.id'> |
|
{{p.name}} |
|
<input v-model='playerList[p.id].name' @input='updatePlayer($event, p.id)' /><button :disabled='delInPrg.includes(p.id)' @click='rmvPlayer(p.id)'>[x]</button> |
|
</div> |
|
|
|
</div> |
|
</template> |
|
|
|
<script> |
|
import connection from '@/connection' |
|
|
|
function shareDbErr(err) { |
|
// eslint-disable-next-line |
|
if (err) { console.error(err); return; } |
|
} |
|
|
|
|
|
export default { |
|
name: 'app', |
|
data(){ |
|
return{ |
|
areaName:'players', |
|
newPlayer:'', |
|
socketState:'', |
|
delInPrg:[], |
|
playerList:{} |
|
} |
|
}, |
|
metaInfo() { |
|
return { |
|
title: `ShareDB (${Object.values(this.playerList).length})` |
|
} |
|
}, |
|
mounted(){ |
|
const doc = connection((v)=>this.socketState = v).createSubscribeQuery(this.areaName, {}) |
|
const _this = this |
|
const setRes = (data, unsubscribe) => { |
|
const res = connection().get(this.areaName, data.id) |
|
const addOrUpdate = p => _this.$set(_this.playerList, p.id, {id:p.id, ...p.data}) |
|
res.on('op', () => { |
|
addOrUpdate(res) |
|
}) |
|
if(!unsubscribe){ |
|
res.subscribe(err=> { |
|
if (err) throw err; |
|
addOrUpdate(res) |
|
}) |
|
} |
|
else{ |
|
res.unsubscribe(err=> { |
|
if (err) throw err; |
|
_this.$delete(_this.playerList, res.id) |
|
}) |
|
} |
|
} |
|
doc.on('ready', () => { |
|
doc.results.forEach(p=>setRes(p)) |
|
}) |
|
doc.on('insert', newData => { |
|
newData.forEach(p=>setRes(p)) |
|
}) |
|
doc.on('remove', removedData => { |
|
removedData.forEach(p=>setRes(p, true)) |
|
}) |
|
}, |
|
methods:{ |
|
addPlayer(){ |
|
const id = (Math.floor(Math.random() * (1000 - 5 + 1)) + 5).toString() |
|
const newPlayer = { name: this.newPlayer, score:id, created:Date.now()} |
|
connection().get(this.areaName, id).create(newPlayer, shareDbErr) |
|
this.newPlayer = '' |
|
}, |
|
updatePlayer(e, id){ |
|
var op = [{p: ['name'], oi: e.target.value}]; |
|
connection().get(this.areaName, id).submitOp(op, shareDbErr); |
|
}, |
|
rmvPlayer(id){ |
|
this.delInPrg = [...this.delInPrg, id] |
|
connection().get(this.areaName, id).del(shareDbErr) |
|
} |
|
} |
|
} |
|
</script> |
|
|