CoffeeScriptでJQueryを使う時の「this」
2052 ワード
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()
Author And Source
この問題について(CoffeeScriptでJQueryを使う時の「this」), 我々は、より多くの情報をここで見つけました https://qiita.com/a12345/items/f77c2cb79f5676b6e4b0著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .