Skip to content

Instantly share code, notes, and snippets.

@hrumhrumble
Created March 10, 2016 18:36
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 hrumhrumble/646bdf448dfa9af2bff2 to your computer and use it in GitHub Desktop.
Save hrumhrumble/646bdf448dfa9af2bff2 to your computer and use it in GitHub Desktop.
class Likes
constructor: ->
@post = $('.post_show')
@post_id = @post.data('post_id')
@counter = @post.find('.counter')
@heart_btn = @post.find('.post_like')
@bindEvent(@heart_btn)
bindEvent: (btn) ->
that = @
btn.on 'click', ->
return that.like() if btn.hasClass('like')
return that.unlike() if btn.hasClass('liked')
like: ->
@sendRequest('like')
unlike: ->
@sendRequest('unlike')
setCounter: (count)->
@counter.text(count)
setClass: (action) ->
return @heart_btn.addClass('liked').removeClass('like') if action == 'like'
return @heart_btn.removeClass('liked').addClass('like') if action == 'unlike'
sendRequest: (action)->
that = @
$.ajax
url: "/posts/#{that.post_id}/#{action}"
type: 'POST',
dataType: 'json',
beforeSend: ->
console.log 'before send'
success: (data)->
that.setCounter(data.count)
that.setClass(action)
error: (data)->
alert data.responseJSON.error
$(document).on('ready page:load', -> new Likes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment