user9235753
user9235753

Reputation:

How to implement "on" method in signalR?

I'm using signalR with the lastest version and I want to improve the on method:

var connection = new signalR.HubConnection('/chat');

connection.on('greeting', msg => $log(msg));
connection.on('sayhello', msg => $log(msg));

My goal looks like this:

connection
    .on('greeting', msg => $log(msg))
    .on('sayhello', msg => $log(msg));

How can I do that? Thank you!

Upvotes: 1

Views: 47

Answers (1)

Lansana Camara
Lansana Camara

Reputation: 9873

If the package you are using doesn't allow chaining (meaning it doesn't return the instance in the on method), then you can create a wrapper to achieve what you want.

class MyConnection {
    connection;

    constructor(connection) {
        this.connection = connection;
    }

    on(key, callback) {
        this.connection.on(key, callback);
        return this;
    }
}

Now apply like so:

var myConnection = new MyConnection(connection);

myConnection.on('greeting', msg => $log(msg))
            .on('sayhello', msg => $log(msg));

This approach is usually taken in enterprise software (at least in the server side) because it allows you to do a few things:

  1. Extend the third party package to add your domain-specific logic
  2. Wrap it in a way that makes it easier to test with your system
  3. Only expose features you want used by developers in the event that you don't want people using all of the third party package

Upvotes: 1

Related Questions