Consider the following code:
var connection = new signalR.HubConnectionBuilder().withUrl("/hub").build();
connection.on("ReceiveMessage", (message) => {
console.log("Once");
});
connection.on("ReceiveMessage", (message) => {
console.log("Twice");
});
Now when the server sends ReceiveMessage
to the client, the browser's console contains... both Once
and Twice
. Apparently, both functions are invoked.
Problem is, in of my inexperience & lack of knowledge I assumed that registering a new function for the same command (ReceiveMessage
in this case) will automatically repleace the previously registered function, if there was any. And I was writing my program with that assumption. I only had to verify this assumption once I started noticing bizzarre behavior of my program.
Can I somehow deregister previously registered handlers? Or should I rewrite my JS code with the assumption that I should only register one function per connection per command?
Yes, all handlers can be unregistered with just the method name.
var connection = new signalR.HubConnectionBuilder().withUrl("/hub").build();
connection.off("ReceiveMessage");
connection.on("ReceiveMessage", (message) => {
console.log("Once");
});
connection.off("ReceiveMessage");
connection.on("ReceiveMessage", (message) => {
console.log("Twice");
});