Feeliiix
Feeliiix

Reputation: 11

Socket.io Typescript Custom Arguments

I have a question. I'm trying to use Socket.io with Typescript.

Therefore I'm using this definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/socket.io-client/socket.io-client.d.ts

Now to my question. How does I have to use the socket.once method, when I send the custom arguments "example: true" using the socket.emit method?

My code for the NodejS server:

socket.once("example-event-request", {
    socket.emit("example-event-response", {example: true});
});

Browser when need the data:

socket.emit("example-event-request");

socket.once("example-event-response", (data) => {
    this.example = data.example;
});

Added as an Answer (likely to be deleted soon):

I want to specify this more. I need to write this JavaScript code in Typescript using the linked definitions.

this.socket.once(eventName, function(){
    callback.apply(this.socket, args);
});

this.socket.emit(eventName, data, function(){
    callback.apply(this.socket, args)
});

The problem is that I cannot get the args because there is no Typescript variable for this.

Upvotes: 1

Views: 771

Answers (1)

basarat
basarat

Reputation: 276161

The emit and the once cannot be on the same side. You emit from server to client or client to server. And the once belongs on the other side.

Also "{example: true}" should probably be {example: true} i.e. a json serializable object (not a string).

More

if you are looking to do rpc I have an example project (alm) that abstracts that over socket io (or inter process ipc): https://basarat.gitbooks.io/alm/content/contributing/async.html

Upvotes: 1

Related Questions