March 18, 2013
JQuery on click not working
Question by Jamie Fearon
I’m having strange behaviour where within the same file a change event is working but a click event isn’t. I understand I may have not posted enough code, but I just want to see if anyone knows why on event may work but another will not. Here is my code:
class AddBTS
constructor: () ->
$('#a').on 'change', (evt) => @a evt
$('#b').on 'change', (evt) => @b evt
$('#c').on 'click', (evt) => @c
a: (evt) =>
console.log 'a works'
b: (evt) =>
console.log 'b works'
c: () =>
console.log 'c works'
The html it refers to:
<input type="file" id="a">
<input type="file" id="b">
<button id="c">OK</button>
The events work fine on a and b, but the click event doesn’t work on c.
My compiled JS is executed after the DOM loads.
Could anyone give me some pointers on what may cause this and I will try it out.
Interestingly, when I double click on c I get the following error:
Error in event handler for 'undefined': IndexSizeError: DOM Exception 1 Error: Index or size was negative, or greater than the allowed value.
Answer by user1737909
You have to call your c function :
@c()
Without parens, you’re only accessing it. Remember, CoffeeScript isn’t Ruby ;).