javascript - Why is myVar undefined? -
when socket event drawmouse
& draw()
function called myvar
undefined. why can't access this.myvar
within socket.on callback?
import { component, oninit } '@angular/core'; import * io '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 undefined console.log(this.myvar); } }
because this
inside socket callback not refering component.
try:
this.socket.on('drawmouse', (data)=>{ this.draw(data) })
Comments
Post a Comment