简体   繁体   中英

Rails 4: Upvote/Downvote with coffeescript

It's similar like it is here on stackoverflow- you can upvote a comment and when you do it is marked with orange arrow. However, I have 2 icons(on & off) for upvote and 2 for downvote. The problem is that when I click on upvote, it changes icon to 'on', which is good, but when I click on downvote after that, upvote stays the same(with on icon). So, I basically get 2 'on' icons.

The goal: When you upvote/downvote and then you decide to change your vote, the icon for previous choice should be 'off'

-my current code-

<div class="thumbsup">
    <%= link_to image_tag('othericons/thumbsup_off.PNG', height: '20', width: '20', id: "imgClickAndChange", :onclick => "window.changeImage($(this))"),  like_post_comment_path(comment.post_id, comment), method: :put, :remote => true %>
</div>

<div class="thumbsdown">
  <%= link_to image_tag('othericons/thumbsdown_off.PNG', height: '20', width: '20', id: "imgClickAndChange", :onclick => "window.toggleImage($(this))"), dislike_post_comment_path(comment.post_id, comment), method: :put, :remote => true %>
</div>

coffeescript

window.changeImage = (source) ->
    console.log "called changeImage(source)"
    $source = $(source)
    imagePath = $source.attr("src")
    if imagePath && imagePath == "/assets/othericons/thumbsup_off.PNG"
      console.log "thumbsup is currently OFF"
      $source.attr("src", "/assets/othericons/thumbsup_on.PNG")
    else
      console.log "thumbsup is currently ON"
      $source.attr("src", "/assets/othericons/thumbsup_off.PNG")

window.toggleImage = (source) ->
    console.log "called changeImage(source)"
    $source = $(source)
    imagePath = $source.attr("src")
    if imagePath && imagePath == "/assets/othericons/thumbsdown_off.PNG"
      console.log "thumbsdown is currently OFF"
      $source.attr("src", "/assets/othericons/thumbsdown_on.PNG")
    else
      console.log "thumbsdown is currently ON"
      $source.attr("src", "/assets/othericons/thumbsdown_off.PNG")

You'd be so much better handling this with data from the server:

#app/controllers/votes_controller.rb
def like
     #your code
     status = "on"
     respond_to do |format|
         format.js { render json: status.to_json }
     end
end

#same for dislike, except status = "off"

Then you can handle the image with with the ajax:success callback:

$(document).on "ajax:success", "#imgClickAndChange", (data) ->
    $(this).attr("src"), "/assets/othericons/thumbsup_"+ data +".PNG")

Currently, I don't even know how your coffeescript is firing? It's not bound to any events?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM