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! :)