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 quotes
Right?
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:
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]
EDIT: Managed to fix the event listener and the buttons (thanks @mu!):
To fix the event listener I had to make a seperate loop later in the code (after the buttons were appended to the page):
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:
Thank you! :)