1

When I get my socket event drawMouse & my draw() function is called myVar is undefined. Why can't I access this.myVar from within the socket.on callback?

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);
  }
}
Justin Young
  • 2,393
  • 3
  • 36
  • 62

1 Answers1

3

Because this inside the socket callback is not refering to the component.

Try:

 this.socket.on('drawMouse', (data)=>{
          this.draw(data)
      })
eko
  • 39,722
  • 10
  • 72
  • 98
  • @FelixKling oh I didn't realize that and how so? :D – eko Nov 10 '16 at 17:33
  • No idea ;) Maybe I'm misinterpreting the text. – Felix Kling Nov 10 '16 at 17:33
  • 1
    @echonax that worked. I guess it's due to trying to using es6 scoping, but not using the new function syntax right? – Justin Young Nov 10 '16 at 18:43
  • @JustinYoung exactly. We were a little confused though whether you actually succeeded in calling the method or not. – eko Nov 10 '16 at 18:45
  • 1
    @echonax Yeah it was calling the method, but when I logged out the value of myVar within the method call it was undefined. Guess it was just getting the lines crossed. Thanks for the help! – Justin Young Nov 10 '16 at 19:17
  • @JustinYoung: *"Yeah it was calling the method"* But that's impossible given your original code. Inside the callback, `this` refers to `window` (or `undefined`), not the instance. – Felix Kling Nov 11 '16 at 23:13