Monday, May 20, 2024
25
rated 0 times [  31] [ 6]  / answers: 1 / hits: 42453  / 13 Years ago, wed, august 31, 2011, 12:00:00

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!


More From » coffeescript

 Answers
64

jQuery.each passes the current element as second parameter of the callback, so you don't have to reserve this for jQuery:



processRows: ->
$(#my-table>tr).each (index, element) =>
id = $(element).attr(id)
@processRow id


Notice the use of the fat arrow (=>) syntax for the callback function; it binds the function's context to the current value of this. (this in the callback function is always the same this as the one at the time you defined the function.)


[#90325] Tuesday, August 30, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kalynnkathrynd

Total Points: 273
Total Questions: 101
Total Answers: 93

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
;