CoffeeScriptでJQueryを使う時の「this」


CoffeeScriptでJQueryのイベント処理を書く際に注意すること

例 クリックした要素のテキストを表示する

html
<ul class="lists">
  <li><a href="#">テキスト1</a></li>
  <li><a href="#">テキスト2</a></li>
  <li><a href="#">テキスト3</a></li>
</ul>
javascript
function Ex() {
  this.setEvent();
}

Ex.prototype.setEvent = function() {
  var _this = this;
  $('.lists li a').on('click', function() {
    var text = $(this).text();
    _this.showText(text);
  });
}
Ex.prototype.showText = function(_text) {
  alert(_text);
}
$(function() {
  var ex = new Ex();
});

上記javascriptをCoffeeScriptで書く

CoffeeScript1
class Ex
  constructor: ()->
    @setEvent()

  setEvent: ()=>
    $('.lists li a').on('click', ()=>
      text = $(@).text()
      @showText(text)
    )

  showText: (_text)=>
    alert(_text)

window.Ex= Ex

$ ()->
  ex = new Ex()

このままだとメソッド「setEvent」の部分で「this」の参照先が違うのでクリックしたエレメントを取得できない。
メソッド「setEvent」の部分を下記のように書き換える。

CoffeeScript2
class Ex
  constructor: ()->
    @setEvent()

  setEvent: ()=>
    #エレメント1つ1つへイベントを設定する
    $('.lists li').each((i, v)=>
      elm = $(v)
      text = elm.find('a').text()
      elm.on('click', ()=>
        @showText(text)
      )
    )

  showText: (_text)=>
    alert(_text)

window.Ex= Ex

$ ()->
  ex = new Ex()