Last active
August 29, 2015 14:11
-
-
Save kawabataryo/b870a5c3623c79d3f2d6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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を使用するとこの現象は起こらない。 | |
| */ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | |
| } | |
| } |
Author
なるほど、イベントリスナーに直接関数を書くと動くとこまではできたけど、なんとか関数を切り分けたかったので、これなら動きますね。助かりました。 ⇒ modified.js
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
addEventListenerに渡した関数内のthisが参照するのは基本イベント発火元になるはずで
initでやっていることを書きかえると
となり、「TextCount.lenderTextCountに代入してる関数定義をaddEventListenerに渡す」というプログラムになります。
やりたいことは、イベント発火時に「TextCountクラスのインスタンスが持つlenderTextCountメソッドを実行させる」こと。つまり「that.lenderTextCountを実行してくれる関数定義をaddEventListenerに渡す」というプログラムを書きたいということになると思われるので
で解決できるんじゃないかと思います。
サンプル作って試してみました
http://jsdo.it/okomeworld/84R2