5
5

More than 5 years have passed since last update.

CoffeeScriptでファットアローを使用した場合のthisについて

Posted at

CoffeeScriptでファットアローを使用してthisコンテキストを維持した場合、イベントハンドラ内の関数にthisを引数として渡す方法がよく分からなかったので試してみました。
分かりづらい説明になってしまいましたので、ソースをご確認頂ければと思います。

hoge.coffee
class Hoge
  constructor: ->
    @button = document.getElementById 'button'
    @attachEvent()

  attachEvent: ->
    @button.addEventListener 'click', => # ファットアローを使用してthisコンテキストを維持
      @addClass(@) # クリックした要素を渡したいが、ここでの@はHogeを指しているため意図しない挙動になる
    , false

  addClass: (target) ->
   target.className = 'is-active'

結局、下記のようにeventオブジェクトのcurrentTargetを渡してあげる事で解決しました。

hoge.coffee
class Hoge
  constructor: ->
    @button = document.getElementById 'button'
    @attachEvent()

  attachEvent: ->
    @button.addEventListener 'click', (e) =>
      @addClass(e.currentTarget) # これでクリックした要素を渡せた
    , false

  addClass: (target) ->
   target.className = 'is-active'
5
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5