From 1c6ff47d8b585fde43a61a8f7807339d4dbff5f3 Mon Sep 17 00:00:00 2001 From: Dan Barber Date: Sun, 11 Mar 2018 19:47:29 -0400 Subject: [PATCH] Refactor channel service --- assets/js/app.js | 27 ++++++--------------------- assets/js/services/channel.js | 35 +++++++++++++++++++++++++++++------ 2 files changed, 35 insertions(+), 27 deletions(-) diff --git a/assets/js/app.js b/assets/js/app.js index 3605b72..d020f6f 100644 --- a/assets/js/app.js +++ b/assets/js/app.js @@ -8,40 +8,25 @@ import ReactDOM from "react-dom"; import { createStore } from "redux"; import { Provider } from "react-redux"; -import chessBoardReducer from "./reducers/chess-board"; - -const store = createStore(chessBoardReducer); - -import { setPlayer, setGame, setGameId } from "./store/actions"; - -import API from "./services/api"; import Channel from "./services/channel"; +import chessBoardReducer from "./reducers/chess-board"; +import { setPlayer, setGame, setGameId } from "./store/actions"; import ChessBoard from "./components/chess-board"; +const store = createStore(chessBoardReducer); + class App extends React.Component { componentWillMount() { const { gameId, store } = this.props; store.dispatch(setGameId(gameId)); - this.channel = Channel.gameChannel(gameId); - - this.channel.on("game:update", data => { - if (data.player != undefined) { - store.dispatch(setPlayer(data.player)); - }; - store.dispatch(setGame(data)); - }); - - this.channel.join() - .receive("error", resp => { - console.log("Unable to join", resp); - }); + this.channel = new Channel(store, gameId); } sendMove(gameId, move) { - this.channel.push("game:move", move); + this.channel.sendMove(move); } render() { diff --git a/assets/js/services/channel.js b/assets/js/services/channel.js index 1313eeb..739cd38 100644 --- a/assets/js/services/channel.js +++ b/assets/js/services/channel.js @@ -1,11 +1,34 @@ import socket from "../socket"; +import { setPlayer, setGame } from "../store/actions"; -const Channel = { - gameChannel: (gameId) => { - const channel = socket.channel(`game:${gameId}`, {}); +class Channel { + constructor(store, gameId) { + this.store = store; + this.channel = socket.channel(`game:${gameId}`, {}); - return channel; - }, -}; + this.join(); + this.subscribe(); + } + + join() { + this.channel.join() + .receive("error", resp => { + console.log("Unable to join", resp); + }); + } + + subscribe() { + this.channel.on("game:update", data => { + if (data.player != undefined) { + this.store.dispatch(setPlayer(data.player)); + }; + this.store.dispatch(setGame(data)); + }); + } + + sendMove(move) { + this.channel.push("game:move", move); + } +} export default Channel;