Reputation:
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
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:
Upvotes: 1