Skip to content

Instantly share code, notes, and snippets.

@nickw
Created December 21, 2012 00:03
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 nickw/4349723 to your computer and use it in GitHub Desktop.
Save nickw/4349723 to your computer and use it in GitHub Desktop.
CH.Concerns.Voteable =
incrementScore: ->
score = parseInt(@get("score"), 10)
@set "score", score+1
decrementScore: ->
score = parseInt(@get("score"), 10)
@set "score", score-1
doVote: (direction, silent=false) ->
if direction is "up"
ids = @get("up_voter_ids")
ids.push CH.CurrentUser.get("id")
@set "up_voter_ids", ids
@incrementScore()
else if direction is "down"
ids = @get("down_voter_ids")
ids.push CH.CurrentUser.get("id")
@set "down_voter_ids", ids
@decrementScore()
CH.CurrentUser.set "number_of_votes_performed", parseInt(CH.CurrentUser.get("number_of_votes_performed"), 10) + 1
@trigger("vote:changed") unless silent
removeVote: (direction, silent=false) ->
if direction is "up"
@set "up_voter_ids", _(@get("up_voter_ids")).without(CH.CurrentUser.get("id"))
@decrementScore()
else if direction is "down"
@set "down_voter_ids", _(@get("down_voter_ids")).without(CH.CurrentUser.get("id"))
@incrementScore()
CH.CurrentUser.set "number_of_votes_performed", parseInt(CH.CurrentUser.get("number_of_votes_performed"), 10) - 1
@trigger("vote:changed") unless silent
# --------------------------------------------------------------------------------------------------------
class CH.Views.VoteButtonView extends Backbone.View
events:
"click a[data-vote-direction=up]": "voteUp"
"click a[data-vote-direction=down]": "voteDown"
initialize: (@options = options) ->
@model.bind("vote:changed", @render)
render: =>
template: ->
@$el.html(HAML["voteButton"](@))
if CH.CurrentUser.voted(@model, "up")
@$(".vote-button-arrow-up").addClass("active")
else if CH.CurrentUser.voted(@model, "down")
@$(".vote-button-arrow-down").addClass("active")
voteUp: (event) ->
event.preventDefault()
@doVote(@model.upVoteURL(), "up")
voteDown: (event) ->
event.preventDefault()
@doVote(@model.downVoteURL(), "down")
doVote: (href, direction) ->
oppositeDirection = if direction is "up" then "down" else "up"
if CH.CurrentUser.voted(@model, direction)
@model.removeVote(direction)
else
@model.removeVote(oppositeDirection, true) if CH.CurrentUser.voted(@model, oppositeDirection)
@model.doVote(direction)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment