Created
July 6, 2016 15:23
-
-
Save aysbg/477db5b99bd2979a0be2d3d984a3612f to your computer and use it in GitHub Desktop.
Store pattern implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Store implementation: | |
import { EventEmitter } from 'events'; | |
const store = new EventEmitter(); | |
let game = {}; | |
store.GAME = () => { | |
return game; | |
}; | |
store.updateGame = (id, gameData) => { | |
return fetch(`/game/${id}/data`, { | |
method: 'PUT', | |
headers: { | |
'Accept': 'application/json', | |
'Content-Type': 'application/json' | |
}, | |
body: gameData | |
}) | |
.then(parseJSON) | |
.then(function(data) { | |
store.emit('game-updated', data); | |
game = data; | |
return game; | |
}) | |
.catch(handleError); | |
}; | |
function parseJSON(response) { | |
return response.json() | |
} | |
function handleError(response) { | |
let error = new Error(response.statusText); | |
error.response = response; | |
console.error(error); | |
throw error; | |
} | |
/// Implementation in components where we update | |
import store from 'store'; | |
store.updateGame(gameId, {}).then(() => toastr.success('Yey!')).catch(handleHttpError) | |
function handleHttpError(error) { | |
toastr.error('Something went wrong...') | |
console.error(error); | |
} | |
// Implementation in listeners for updates | |
// somewhere when component is created/ready | |
import store from 'store'; | |
store.on('game-updated', this.handleGameUpdated) | |
function handleGameUpdated(data) { | |
... do your processing logic here. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment