2016-11-10 9 views
1

私のソケットイベントを取得するときdrawMouse &私のdraw()関数が呼び出されますmyVarは未定義です。 socket.onコールバックからthis.myVarにアクセスできないのはなぜですか?なぜmyVarは未定義ですか?

import { Component, OnInit } from '@angular/core'; 

import * as io from 'socket.io-client'; 


@Component({ 
    selector: 'app-test', 
    templateUrl: './test.component.html', 
    styleUrls: ['./test.component.css'] 
}) 
export class TestComponent implements OnInit { 
    myVar:string; 

    constructor(){ 
    this.socket = io("http://localhost:4300"); 
    this.myVar = "hello" 

    } 

    ngOnInit() { 
     this.socket.on('drawMouse', function(data){ 
      this.draw(data) 
     }) 
    } 

    draw(){ 
    //this variable is undefined 
    console.log(this.myVar); 
    } 
} 
+2

と呼ばれていますか?そうは思わない。 –

+0

ほとんどの場合、[コールバック内の正しい 'this'/contextにアクセスするにはどうすればいいですか?](http://stackoverflow.com/q/20279484/218196) –

答えて

3

ソケットコールバック内部thisコンポーネントに参照のうえないからです。

試してください:あなたは確か `draw`は実際に

this.socket.on('drawMouse', (data)=>{ 
      this.draw(data) 
     }) 
+1

しかしOPは' draw'関数.... –

+0

@FelixKlingああ私はそれを理解していないとどのように? :D – echonax

+0

いいえ考え;)たぶん私はテキストを誤解しています。 –

関連する問題