Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoffeeScript - Binding Click Events to Dynamically Loaded Objects With JQuery On

Tags:

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!

like image 673
CHawk Avatar asked Jan 15 '12 21:01

CHawk


2 Answers

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.

like image 117
Epeli Avatar answered Nov 09 '22 00:11

Epeli


$(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).

like image 26
Lucero Avatar answered Nov 09 '22 02:11

Lucero