I'm having trouble with creating multiple buttons and matching event listeners in the CoffeeScript part of my ActionCable channel. I'm aware of the different concatenation methods for single quoted text (Literal Strings) and double quoted text (Strings):
"#{first_name} McFly"
for double quotesfirst_name + ' McFly'
for single quotesRight?
So I'm a bit confused why this doesn't seem to work:
answer_text = "answer_button_"
counter = 0
for i in data.answers
answerHtml.push "<button type='button' id=answer_text+counter >#{i.title}</button>"
$('#'+answer_text+counter).on 'click', (e) -> App.answer_data.send_data()
counter = counter+1
I've been stuck on this part for too long already, so I'd be really happy if anyone could give me a nudge in the right direction :)
Ok, so the problem was with the first part of the on click handler - the expression in the braces needed to be enclosed in single quotes. For example:
$('#answer_button_0').on 'click', (e) -> App.answer_data.send_data()
But to be able to concatenate single quotes onto the front and back of my String without turning it into a Literal String I had to escape the single quotes by using $.parseHTML("\'")
.
So what finally worked for me was this: [EDIT: turns out this was not the solution, see below]
$($.parseHTML("\'" + '#' + answer_text + counter + "\'")).on 'click', (e) -> App.answer_data.send_data()
EDIT: Managed to fix the event listener and the buttons (thanks @mu!):
answer_text = "answer_button_"
counter = 0
for answer in data.answers
answerHtml.push "<button type='button' id=#{answer_text+counter} >#{answer.title}</button>"
counter = counter+1
To fix the event listener I had to make a seperate loop later in the code (after the buttons were appended to the page):
counter = 0
for id in data.answers.map (answer) -> answer.id
console.log "[AC] answer id: #{i.id}" #This prints 4 different ids, like it should!
$('#answer_button_'+counter).on 'click', (e) -> App.answer_data.send_data(id)
counter = counter+1
Unfortunately, now that the buttons and the event listeners work I have the problem, that the id property that I pass on with the event listeners created in the new loop (at send_data(id)
) is always the same - independent from which button I press. I have no idea why... :/
EDIT 2: As @mu suggested I added the do keyword and now it works:
counter = 0
for id in data.answers.map (answer) -> answer.id
do (id) ->
$('#answer_button_'+counter).on 'click', (e) -> App.answer_data.send_data(id)
counter = counter+1
Thank you! :)