LoginSignup
2
2

More than 5 years have passed since last update.

CoffeeScriptでJQueryを使う時の「this」

Posted at

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()

2
2
0

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
2
2