Skip to content

Instantly share code, notes, and snippets.

@kawabataryo
Last active August 29, 2015 14:11
Show Gist options
  • Select an option

  • Save kawabataryo/b870a5c3623c79d3f2d6 to your computer and use it in GitHub Desktop.

Select an option

Save kawabataryo/b870a5c3623c79d3f2d6 to your computer and use it in GitHub Desktop.
function TextCount(){
this.textArea = document.getElementById('textArea');
this.textCount = document.getElementById('textCount');
this.init();
}
TextCount.prototype = {
init: function(){
var that = this;
that.textArea.addEventListener('keydown', that.renderTextCount)
},
getText: function(){
return this.textArea.value;
},
getTextLength: function(){
return this.getText().length;
},
renderTextCount: function(){
var that = this;
that.textCount.innerHTML = that.getTextLength();
};
}
/*
問題点
イベントリスナーのコールバック関数として使用するとlenderTextCout内で変数に格納したthisまで書き換えられてしまう。
※jQueryの.onを使用するとこの現象は起こらない。
*/
function TextCount(){
this.textArea = document.getElementById('textArea');
this.textCount = document.getElementById('textCount');
this.init();
}
TextCount.prototype = {
init: function(){
var that = this;
that.textArea.addEventListener('keydown', function(){
that.renderTextLength();
});
},
getText: function(){
return this.textArea.value;
},
getTextLength: function(){
return this.getText().length;
},
renderTextLength: function(){
this.textCount.innerHTML = this.getTextLength();
}
}
@okomeworld
Copy link

addEventListenerに渡した関数内のthisが参照するのは基本イベント発火元になるはずで
initでやっていることを書きかえると

// 第2引数のfunction定義はTextCount.lenderTextCountと全く同じ
that.textArea.addEventListener('keydown', function(){
  var that = this; // ← このthisはthat.textAreaになる
  that.textCount.innerHTML = that.getTextLength();
});

となり、「TextCount.lenderTextCountに代入してる関数定義をaddEventListenerに渡す」というプログラムになります。

やりたいことは、イベント発火時に「TextCountクラスのインスタンスが持つlenderTextCountメソッドを実行させる」こと。つまり「that.lenderTextCountを実行してくれる関数定義をaddEventListenerに渡す」というプログラムを書きたいということになると思われるので

// 第2引数のfunciton定義は「インスタンスのlenderTextCountを実行する」という内容
that.textArea.addEventListener('keydown', function(){ that.lenderTextCount() });

で解決できるんじゃないかと思います。

サンプル作って試してみました
http://jsdo.it/okomeworld/84R2

@kawabataryo
Copy link
Author

なるほど、イベントリスナーに直接関数を書くと動くとこまではできたけど、なんとか関数を切り分けたかったので、これなら動きますね。助かりました。 ⇒ modified.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment