How can I combine function calls in JavaScript?

Mr. Jo :

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...

Delena Malan :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=390974&siteId=1