0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

イベントハンドラで@(this)を使用する場合の注意

0
Last updated at Posted at 2016-04-25
example.coffee
class Hoge
  constructor: (message) ->
  	@message = message
  	$("form").on "submit" (event) ->
  		_fuga.call(@)
  
  _fuga = ->
  	alert @message

上記のコードは正しく動かない。
プライベートメソッド _fuga 中で @message を参照しようとしているが、undefined となる。

理由は、イベントハンドラではthisがイベント発生元のオブジェクトを指すようになっているのが原因。
それを回避するには、あらかじめ _this など別の変数に this を退避しておきイベントハンドラ内では _this を参照するように変更すれば良い。

CoffeeScriptではそのようなケースのショートカットとして => が用意されている。
前述のコードを書き直すと以下のとおりとなる。

example2.coffee
class Hoge
  constructor: (message) ->
  	@message = message
  	$("form").on "submit" (event) =>
  		_fuga.call(@)
  
  _fuga = ->
  	alert @message

参考

CoffeeScriptでjQuery使うときのメモ | webOpixel

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?