1
0
mirror of https://github.com/danbee/chess synced 2025-03-04 08:39:06 +00:00

Refactor channel service

This commit is contained in:
Daniel Barber 2018-03-11 19:47:29 -04:00
parent fe0c58917f
commit 1c6ff47d8b
Signed by: danbarber
GPG Key ID: 931D8112E0103DD8
2 changed files with 35 additions and 27 deletions

View File

@ -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() {

View File

@ -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;