diff --git a/assets/js/services/channel.js b/assets/js/services/channel.js index b21b98d..f817db3 100644 --- a/assets/js/services/channel.js +++ b/assets/js/services/channel.js @@ -1,6 +1,6 @@ import _ from "lodash"; import socket from "./socket"; -import { Presence } from "phoenix"; +import Presences from "./presences"; import { setUserId, setPlayers, @@ -13,12 +13,16 @@ class Channel { constructor(store, gameId) { this.store = store; this.channel = socket.channel(`game:${gameId}`, {}); - this.presences = {}; + this.presences = new Presences(); this.join(); this.subscribe(); } + get opponentId() { + return this.store.getState().opponentId; + } + join() { this.channel.join() .receive("error", resp => { @@ -34,12 +38,12 @@ class Channel { this.channel.on("game:update", this.updateGame.bind(this)); this.channel.on("presence_state", data => { - this.presences = Presence.syncState(this.presences, data); + this.presences.syncState(data); this.setOpponentStatus(); }); this.channel.on("presence_diff", data => { - this.presences = Presence.syncDiff(this.presences, data); + this.presences.syncDiff(data); this.setOpponentStatus(); }); } @@ -54,16 +58,10 @@ class Channel { setOpponentStatus() { this.store.dispatch(setOpponentStatus( - this.opponentOnline() ? "viewing" : "offline" + this.presences.opponentOnline(this.opponentId) ? "viewing" : "offline" )); } - opponentOnline() { - return _.find(this.presences, (value, id) => { - return parseInt(id) == this.store.getState().opponentId; - }); - } - getAvailableMoves(square) { this.channel.push("game:get_available_moves", { square }) .receive("ok", (data) => { diff --git a/assets/js/services/presences.js b/assets/js/services/presences.js new file mode 100644 index 0000000..4d88833 --- /dev/null +++ b/assets/js/services/presences.js @@ -0,0 +1,24 @@ +import _ from "lodash"; +import { Presence } from "phoenix"; + +class Presences { + constructor() { + this.presences = {}; + } + + syncState(data) { + this.presences = Presence.syncState(this.presences, data); + } + + syncDiff(data) { + this.presences = Presence.syncDiff(this.presences, data); + } + + opponentOnline(opponentId) { + return _.find(this.presences, (value, id) => { + return parseInt(id) == opponentId; + }); + } +} + +export default Presences;