Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Store pattern implementation
// 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
You can’t perform that action at this time.