2016-08-06 36 views
1

私は何が欠けているか分からない。この1つはそうではないTypescript未定義の 'addEventListener'プロパティを読み取ることができません

Uncaught TypeError: Cannot read property 'addEventListener' of undefined"

class Editor{ 
    public context: CanvasRenderingContext2D; 
    constructor(public canvas: HTMLCanvasElement){ 
     this.context = this.canvas.getContext("2d"); 
     this.canvas.addEventListener("mousedown", this.handleMouseDown); 
    } 
    handleMouseDown(ev: MouseEvent){ 
     this.canvas.addEventListener("mousemove", this.handleMouseMove); 
     //this.handleMouseMove(ev); 
    } 
    handleMouseMove(ev: MouseEvent){ 
     console.log(ev); 
     console.log(ev.target); 
    } 
} 

//============================================================================== 
//declare variables. 

let mapEditor = new Editor(<HTMLCanvasElement>document.getElementById("map-editor")); 

::次のコードは、このエラーが返されます

let cnv = document.getElementById("map-editor") as HTMLCanvasElement; 
cnv.addEventListener("mousedown", handleMouseDown); 

function handleMouseDown(ev: MouseEvent){ 
    ev.target.addEventListener("mousemove", handleMouseMove); 
    handleMouseMove(ev); 
}; 

function handleMouseMove(ev: MouseEvent){ 
    console.log(ev); 
    console.log(ev.target); 
}; 

私は周りを見て、順番を少し変更しようとしましたが、私がすることはできませんイベントを発射する。おそらく私はその言語の重要な要素を見逃していたでしょうか?

編集: 私は、マウスダウンイベントがトリガされたときに、コンテキストを変更していないので、「これ」キーワードは、もはやクラスのインスタンスを参照することを考えます。そのためthis.canvasは定義されていません。私はメソッドとイベントをバインドする方法を変更しようとします。

私はここでの説明が見つかりました:'this'-in-TypeScript

+0

あなたは変化する文脈で正しい軌道に乗っています。太矢印の構文を使って 'this'を字句解析することができます。 – Alex

+0

ありがとうございました、あなたの提案のおかげで本当に太い矢印のソリューションが見つかりました。私はまだこれらの原則とバインディングを理解するのに苦労していますが、私はここに来ています。 –

答えて

2

problemeが変化するコンテキストから来ました。クラスエディタはキャンバスにイベントリスナーを追加します(この場合は「mousedown」)。しかし、イベントが発生し、メソッドが呼び出されると、 'this'はカンバス要素を参照し、含まれるクラスを参照しません。したがって、メンバーにアクセスしようとすると、この場合 'canvas'.canvas、それは未定義です。 Alexによって提案されたような解決策、次のように脂肪の矢印を使用してメソッドを呼び出すときに、クラスのインスタンスに「この」バインドを辞書的にすることでした。ここでは

myClass.member.addEventListener("event", (e) => myClass.handleEvent(e)); 

は私のソリューションです:

class Editor{ 
    public context: CanvasRenderingContext2D; 
    public rect: ClientRect; 
    constructor(public canvas: HTMLCanvasElement){ 
     this.context = this.canvas.getContext("2d"); 
     this.rect = this.canvas.getBoundingClientRect(); 
     this.canvas.addEventListener("mousedown", (ev) => this.handleMouseDown(ev)); 
    } 
    handleMouseDown(ev: MouseEvent){ 
     console.log(this); 
     this.canvas.addEventListener("mousemove", (ev) => this.handleMouseMove); 
    } 
    handleMouseMove(ev: MouseEvent){ 
     console.log(this); 
    } 
    getGridCoordinate(x: number, y: number){ 
    //This should return the correct grid coordinate. 
     return { 
      x: x - this.rect.left, 
      y: y - this.rect.top 
     }; 
    } 
} 
関連する問題