考虑以下代码:
var connection = new signalR.HubConnectionBuilder().withUrl("/hub").build();
connection.on("ReceiveMessage", (message) => {
console.log("Once");
});
connection.on("ReceiveMessage", (message) => {
console.log("Twice");
});
现在,当服务器向客户端发送 ReceiveMessage
时,浏览器的控制台包含... Once
和 Twice
。显然,这两个函数都被调用了。
问题是,由于我缺乏经验和缺乏知识,我假设为同一命令注册一个新函数(在本例中为 ReceiveMessage )将自动替换以前注册的函数(如果有) 。我就是根据这个假设来编写我的程序的。一旦我开始注意到我的程序有奇怪的行为,我就必须验证这个假设。
我可以以某种方式注销以前注册的处理程序吗?或者我应该重写我的 JS 代码,假设我应该只为每个命令的每个连接注册一个函数?
最佳答案
是的,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");
});
关于signalr.client - 如何从 SignalR 客户端取消注册函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50731084/