Reputation: 5261
I'm currently developing a WebSocket. For that purpose I've created a JavaScript class. In this class I've 2 methods: subscribe()
and bind()
. The first method subscribes to a channel and the next one should listen to it.
But when I call my methods this way:
let socket = new CustomWebSocket();
socket.subscribe("my-channel").bind("my-event", function (response) {
console.log(response);
});
I'm getting an error message in my console:
Uncaught TypeError: socket.subscribe(...).bind is not a function
This is how I wrote my functions inside my CustomWebSocket
class:
subscribe(channelName) {
let self = this;
let subMsg = {
type: "subscribe",
channel: channelName
};
self.ws.send(JSON.stringify(subMsg));
return channelName;
}
bind(eventName, callback) {
let self = this;
self.ws.onmessage = function (event) {
let eventData = JSON.parse(event.data);
if (eventData.type === "channelMessage") {
callback(eventData.payload);
}
}
}
What did I wrong? It thought it can work this way...
Upvotes: 0
Views: 34
Reputation: 11424
You're returning channelName;
from subscribe
. So you're effectively trying to call bind
on channelName
.
To be able to call bind
on the return value of subscribe
, you need to return self
or this
from subscribe
.
Upvotes: 2