简体   繁体   中英

How do I ensure my JS ERB is Turbolinks 5 friendly?

I have some simple JS ERB files that work perfectly the first time around. However, the issue is that when the trigger for the JS is pressed multiple times, it doesn't work client-side (even though it works server-side) - which I suspect is related to Turbolinks 5.

One such example of my JS.erb is this:

$("#a-<%= @answer.id %>-accept-answer i.accepted-answer-checkbox.fa.fa-check-square-o").addClass('fa-check-square voted');
$("#a-<%= @answer.id %>-accept-answer i.accepted-answer-checkbox.fa.fa-check-square-o").removeClass('fa-check-square-o');

That's in my Questions controller & /questions/accept_answer.js.erb .

But, right now, my questions.coffee file is blank.

What's the best way to tackle this?

Honestly, CoffeeScript has Ruby-style interpolation, so the easiest way to convert those would be to just go and do something like

$("#a-#{@answer.id}-accept-answer i.accepted-answer-checkbox.fa.fa-check-square-o").addClass 'fa-check-square voted'
$("#a-#{@answer.id}-accept-answer i.accepted-answer-checkbox.fa.fa-check-square-o").removeClass 'fa-check-square-o'

But what you're trying to do , would probably be better served by toggling those three classes, having them in an initial state that opposes each other, so something like:

$("#a-#{@answer.id}-accept-answer i.accepted-answer-checkbox.fa").click (el) ->
  $.each ['fa-check-square', 'voted', 'fa-check-square-o'], (_, val) ->
    $(el).find('i.accepted-answer-checkbox.fa').toggleClass val

Of course, I could be making it too complex, but this seems to solve the problem of toggling the classes that are desired.

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