I have some coffeescript like the following:
class foo:
@bar = 'bob loblaw'
processRows: ->
$("#my-table>tr").each ->
id = $(this).attr("id")
@processRow id
processRow: (id) ->
console.log @bar + id
So my problem is: I need this to reference the .each context inside the loop to get at id, but I also would like this to reference the class instance inside foo.processRow()—which it does not currently do.
Using something like _this = this outside the .each function and passing it around isn’t a great solution, either, since I reference many class variables inside processRow.
Any thoughts? Am I missing something obvious? Thanks!
jQuery.eachpasses the current element as second parameter of the callback, so you don’t have to reservethisfor jQuery:Notice the use of the fat arrow (
=>) syntax for the callback function; it binds the function’s context to the current value ofthis. (thisin the callback function is always the samethisas the one at the time you defined the function.)