3 ms·
I often have to resort to self = @ when using jQuery in classes. Because of how jQuery binds the queried element to this, and the fat arrow overrides this, the
by d4n3 15y ago
I often have to resort to self = @ when using jQuery in classes.
Because of how jQuery binds the queried element to this, and the fat arrow overrides this, there doesn't seem to be another way to access both your class and the jQuery element in the same function.
for instance:
class ButtonLogger
constructor: ->
@clickedButtons = []
$(document).ready => @init()
init: ->
self = @
$('button').click ->
$button = $(@)
self.clickedButtons.push $button.attr 'id'
- jashkenas 15y agoTry `event.currentTarget`, and `event.target` instead. They're much preferable to having a `self` (representing some random DOM element), and a `this` within a function. $('button').click (e) => @clickedButtons.push $(e.target).attr 'id'