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();
}
}
@kawabataryo
Copy link
Author

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

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