简体   繁体   中英

How can I combine function calls in JavaScript?

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM