Skip to content

Instantly share code, notes, and snippets.

@aysbg
Created July 6, 2016 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aysbg/477db5b99bd2979a0be2d3d984a3612f to your computer and use it in GitHub Desktop.
Save aysbg/477db5b99bd2979a0be2d3d984a3612f to your computer and use it in GitHub Desktop.
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