I'm having a problem calling a class method inside of another method.
In the constructor I assign
this.self = this
And that fixed it when calling from the notify() method, but when I try calling
this.self.convo(id, data2.from);
inside of theGoodStuff when I receive a message, I get a TypeError.
I also had trouble with this but gave up, but it is a related issue.
count(){
console.log(this.users);
console.log(this.subbed,"total users");
}
5575257, 5163800 ] undefined 'total users'
It says undefined for the subbed variable
TypeError: Cannot read property 'convo' of undefined
class Socket {
constructor(id) {
this.self = this;
this.subbed = 0;
this.id = id;
this.users = [];
this.ws = new WebSocket('ws://echo.websocket.org');
this.ws.on('message', this.theGoodStuff);
console.log('readystate',this.ws.readyState);
console.log("created socket with user", id);
}
send(msg){
let soc = this.ws;
if(soc.readyState){
console.log("socket open, sending..");
this.ws.send(msg);
} else {
console.log("socket not open, waiting..");
soc.on('open', function(){
console.log("socket now open, sending..");
soc.send(msg);
});
}
}
convo(to, from) {
this.ws.send('{"event":"pusher:subscribe","data":{"channel":"inbox_convo_' + to + '-' + from + '"}}');
}
notify(user) {
this.users.push(user);
this.self.send('{"event":"pusher:subscribe","data":{"channel":"user_notifications_' + user +'"}}');
}
theGoodStuff(json, flags) {
try {
var data = JSON.parse(json)
, data2 = JSON.parse(data.data);
if( data.channel ) {
var user = /inbox-(.*)/g.exec(data.channel) ? /inbox-(.*)/g.exec(data.channel)[1] : /user_notifications_(.*)/g.exec(data.channel)[1];
}
var id = parseInt(user);
switch( data.event ){
case "pusher_internal:subscription_succeeded":
this.subbed++;
break;
case "pusher:connection_established":
break;
case "notification":
if( data2.notify_type ){
switch( data2.notify_type ){
case "notify_inbox":
// New Convo
this.self.convo(id, data2.from);
this.self.convo(data2.from, id);
break;
default:
break;
}
}
break;
default:
console.log(data);
console.log(data2);
break;
}
} catch (e) {
switch ( e.constructor ) {
case SyntaxError:
break;
default:
console.log(e);
}
}
}
}
module.exports = Socket;
Thanks, any help is greatly appreciated!