2016-11-10 150 views
1

當我得到我的插座事件drawMouse & my 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

確定'draw'實際上是叫什麼名字?這似乎不太可能。 –

+0

最有可能是[如何在回調中訪問正確'this'/context的副本](http://stackoverflow.com/q/20279484/218196) –

回答

3

因爲this插座回調裏面是不是指的組件。

嘗試:

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

但OP似乎認爲'draw'函數被稱爲.... –

+0

@FelixKling哦,我沒有意識到這一點,以及如何如此? :D – echonax

+0

不知道;)也許我誤解了文字。 –