diff --git a/assets/js/app.js b/assets/js/app.js index e7f5c6c..32a8f30 100644 --- a/assets/js/app.js +++ b/assets/js/app.js @@ -5,7 +5,6 @@ import "phoenix_html"; import React from "react"; import ReactDOM from "react-dom"; -import watch from "redux-watch"; import { createStore } from "redux"; import Channel from "./services/channel"; @@ -13,6 +12,7 @@ import Notifications from "./services/notifications"; import chessBoardReducer from "./reducers/chess-board"; import { setGameId } from "./store/actions"; +import Listeners from "./store/listeners"; import ChessBoard from "./components/chess-board"; import MoveList from "./components/move-list"; @@ -27,14 +27,8 @@ class App extends React.Component { store.dispatch(setGameId(gameId)); - let w = watch(store.getState, "turn"); - store.subscribe(w((newVal, oldVal, objectPath) => { - const player = store.getState().player; - - if (oldVal != null && newVal == player) { - notifications.notifyTurn(player); - } - })); + this.listeners = new Listeners(store); + this.listeners.setListeners(notifications); this.channel = new Channel(store, gameId); } diff --git a/assets/js/services/notifications.js b/assets/js/services/notifications.js index 27ae525..75376cf 100644 --- a/assets/js/services/notifications.js +++ b/assets/js/services/notifications.js @@ -4,11 +4,15 @@ class Notifications { } notifyTurn(player) { + this.notify({ + body: "Your opponent has moved.", + icon: `/images/king_${player}.svg`, + }); + } + + notify(options) { if (!document.hasFocus()) { - new Notification("Chess", { - body: "Your opponent has moved.", - icon: `/images/king_${player}.svg` - }); + new Notification("Chess", options); } } } diff --git a/assets/js/store/listeners.js b/assets/js/store/listeners.js new file mode 100644 index 0000000..d3f58c0 --- /dev/null +++ b/assets/js/store/listeners.js @@ -0,0 +1,27 @@ +import watch from "redux-watch"; + +class Listeners { + constructor(store) { + this.store = store; + } + + setListeners(notifications) { + this.notifications = notifications; + + let watcher = watch(this.store.getState, "turn"); + + this.store.subscribe( + watcher(this.notifyTurn.bind(this)) + ); + } + + notifyTurn(newVal, oldVal) { + const player = this.store.getState().player; + + if (oldVal != null && newVal == player) { + this.notifications.notifyTurn(player); + } + } +}; + +export default Listeners;