2016-07-13 2 views
2

私は以下のコードを書いています。ここでは、クラス todosの新しいインスタンスを作成し、毎回別のテキストをコンストラクタに渡しています。ES6で作成された新しいインスタンスごとに別のスコープを渡す

inside setText私はクリックメソッドを要素testにバインドしていますので、それをクリックしてそのテキストを返します。

ここで問題となるのは、このメソッドで作成された3つのコンポーネントには別々のテキストが表示されますが、いずれの要素をクリックしても、最後のテキストは'this is a todo component3'と表示されます。私は、それを各コンポーネントごとに分離したいと思っています。助けてください。

class todos{ 
    constructor(text){ 
    this.istodo = false; 
    this.text = text; 
    } 
    _changestatus(){ 
    this.istodo = !this.istodo; 
    } 
    setText(){ 
    this.getDiv = document.getElementById('test'); 
    this.getDiv.innerHTML = this.getDiv.innerHTML+'\n'+this.text; 
    this.getDiv.onclick = (event)=> {alert(this.text)}; //this is always coming as "this is a todo component3" 
    } 
} 


let todo = new todos('this is a todo component'); 
todo.setText(); 
let todo1 = new todos('this is a todo component1'); 
todo1.setText(); 
let todo2 = new todos('this is a todo component2'); 
todo2.setText(); 
let todo3 = new todos('this is a todo component3'); 
todo3.setText(); 
+0

あなたがいつも使っている 'のdocument.getElementById( 'テスト')は'右 – Holger

+0

はい、おかげで、私はその部分を気付きませんでした。 – Shouvik

答えて

2

問題はすべてのあなたのテキストとあなたが追加したすべての次のTODOのための唯一つの容器を持っているということです、以前のいずれかによって作成されたonclickハンドラが上書きされます。だからこれが問題です。

これを解決するには、すべての実行者がテキスト用に独自のコンテナを作成する必要があります。以下は、これを行う方法の1つです。私がtodosクラスからdocument.getElementById('test')を削除したことに注意してください。

class todos { 
 
     constructor(text) { 
 
     this.istodo = false; 
 
     this.text = text; 
 
     } 
 
     _changestatus() { 
 
     this.istodo = !this.istodo; 
 
     } 
 
     setText() { 
 
     this._node = document.createElement('div'); 
 
     this._node.appendChild(new Text(this.text)); 
 
     this._node.onclick = (event) => { 
 
      alert(this.text) 
 
     }; 
 
     } 
 
     getNode() { 
 
     return this._node; 
 
     } 
 
    } 
 

 
    let container = document.getElementById('test'); 
 

 
    ['this is a todo component', 'this is a todo component #2', 'this is a todo component #3'].forEach(text => { 
 
     let todo = new todos(text); 
 
     todo.setText(); 
 
     container.appendChild(todo.getNode()); 
 
    });
<div id="test"></div>

関連する問題