2016-11-10 152 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

不知道;)也许我误解了文字。 –