Reputation: 375
I'm trying to create a model class for sockette so that I can use that sockette model wherever it is required.
I'm trying to use instance of this sockette model class in other files.
I'm able to do this successfully.
otherFiles.js
:
import Sockette from '../utilities/otherFiles';
const Sockete = new Sockette(url,Id) // creating the instance and passing the parameter values to that instance class
Sockette.ts
:
import sockette from 'sockette';
export default class Sockette {
public ws : any;
public Id : string;
public pingInterval : any;
public dataReceived : any;
public url : string;
constructor(url: string,Id: string){
this.Id = Id;
this.url = url;
this.ws = new sockette(`${url}?Id=${this.Id}`,{onclose: this.onClose,onerror: this.onError,onopen: this.onOpen,onmessage: this.onMessage});
}
public onClose(events: any) {
console.log('Closed!', events);
}
public onError(events:any) {
console.log('Error!', events);
}
public onOpen(events:any) {
console.log("Id :",this.Id) // gives me error that Id is undefined
console.log('Open!', events);
this.ws.json({action:'GET_STATUS', Id: this.Id});
this.pingInterval = setInterval(function() {
this.ws.json({action:'PING'});
},1000);
}
public onMessage(events:any) {
try {
this.dataReceived = JSON.parse(events.data);
} catch(err) {
console.log('Data received not a JSON');
}
if (this.dataReceived && this.dataReceived.action === 'ORDER_STATUS') {
console.log("dataReceived :",this.dataReceived)
return this.dataReceived.value
}
}
}
But If I try to access this.id
or this.ws
in public onOpen()
inside Sockette model it says that it is undefined
Error :
TypeError: Cannot read property 'Id' of undefined
onOpen
28 | }
29 |
30 | public onOpen(events:any) {
31 | console.log("Id :",this.Id)
32 | console.log('Open!', events);
Upvotes: 0
Views: 218
Reputation: 1582
you should bind your functions to this of Sockette class add these lines to constructor
this.onError = this.onError.bind(this);
this.onClose = this.onClose.bind(this);
this.onOpen= this.onOpen.bind(this);
this.onMessage= this.onMessage.bind(this);
Upvotes: 1
Reputation: 198
Try using arrow function
public onOpen(events:any) => {
console.log("Id :",this.Id)
console.log('Open!', events);
this.ws.json({action:'GET_STATUS', Id: this.Id});
this.pingInterval = setInterval(function(){
this.ws.json({action:'PING'});
},1000);
}
Upvotes: 1