Working on rewriting the front-end of my site in Coffeescript. I understand how to bind a click function to a class.
$('.song').click ->
//code
However, I am running into some problems with dynamically loaded content. I know in JQuery, the solution to this would be to use the "On" function like so:
$(document).on('click', '.song', function(){
//code
});
But I am unsure on how this translates to coffeescript. I am under the impression that the rocket arrow -> translates to an anonymous function in javascript, but how does that work with if the function is one of the parameters? I've tried out quite a few different syntax and none of them seem to work, thanks!
Usually one don't use brackets in CoffeeScript if the execution order is clear without them. So this can be written like this:
$(document).on 'click', '.song', ->
### code ###
But of course use brackets always when the execution order is not obvious.
$(document).on('click', '.song', ( ->
### code ###
));
Translates to this JavaScript:
$(document).on('click', '.song', (function() {
/* code */
}));
Note that you may want to use the =>
operator instead of ->
; using the double arrow also binds this
to the event handler (equivalent of using jQuery's bind).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With