Skip to content

Instantly share code, notes, and snippets.

@chrislloyd
Created February 19, 2015 16:37
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 chrislloyd/56687b24dad277db23c2 to your computer and use it in GitHub Desktop.
Save chrislloyd/56687b24dad277db23c2 to your computer and use it in GitHub Desktop.
up vote widget
// in this version, the user clicks the button, the request is sent to the server and the number of upvotes
// is only updated when the response comes back
handleClick: function(e) {
e.preventDefault();
this.upvote();
},
upvote: function() {
// Not sure what the state name is here, just need this to toggle the button immediately
this.setState({current_user_has_upvoted: true})
$.ajax({
url: this.props.game.url + '/upvote',
type: 'POST',
success: function(data) {
// response looks like {votes_up: x}
this.setState({votes_up: data.votes_up});
}.bind(this),
error: function(xhr, status, err) {
console.error(status, err.toString());
}.bind(this)
});
}
// This optimisitic version toggles the button and the count assuming that the request is going to be a-ok. It only adjusts things when the request fails.
handleClick: function(e) {
e.preventDefault();
this.upvote();
},
upvote: function() {
this.setState({
current_user_has_upvoted: true,
votes_up: this.state.votes_up + 1
});
$.ajax({
url: this.props.game.url + '/upvote',
type: 'POST',
// We don't even care about the success case in this version
error: function(xhr, status, err) {
this.setState({
votes_up: this.state.votes_up - 1
});
}.bind(this)
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment