AnthonyGalli.com AnthonyGalli.com - 1 month ago 9
CoffeeScript Question

unexpected -> userSelect.on 'valuesChanged' ->

I ran this code from

challengers.coffee
and I get the error
ActionView::Template::Error (SyntaxError: [stdin]:3:31: unexpected ->
, which I was able to distill down further (see comment at line #3):

$(document).ready ->
userSelect = $('#change-challenge-options')
userSelect.on 'valuesChanged' ->
currentUserId = $('#current-challenge-options').data('current-user-id')
if(currentUserId == userSelect.val())
$('#current-user-challenges').show()
$('#challenged_user_challenges').hide()
else
$('#challenged_user_challenges').show()
$('#current-user-challenges').hide()


dueler/_dueler_fields.html.erb

<%= f.select :user_id, User.order(:name).map { |user| [user.full_name, user.id] }, include_blank: true, id: "change-challenge-options", data: {current_user_id: current_user.id } %> will

<%= collection_select(:dueler, :challenge_id, @current_user_challenges, :id, :full_challenge, include_blank: true, id: "current-user-challenges") %>
<%= collection_select(:dueler, :challenge_id, @challenged_user_challenges, :id, :full_challenge, include_blank: true, id: "challenged_user_challenges") %>

Answer

You have a comma missing before ->. The code should look like (I also removed parentheses in the if statement):

$(document).ready ->
  userSelect = $('#change-challenge-options')
  userSelect.on 'valuesChanged', -> 
    currentUserId = $('#current-challenge-options').data('current-user-id')
    if currentUserId == userSelect.val()
      $('#current-user-challenges').show()
      $('#challenged_user_challenges').hide()
    else
      $('#challenged_user_challenges').show()
      $('#current-user-challenges').hide()