是否可以让 socket.io 客户端响应所有事件,而无需单独指定每个事件?
例如,像这样的东西(显然现在不起作用):
var socket = io.connect("http://myserver");
socket.on("*", function(){
// listen to any and all events that are emitted from the
// socket.io back-end server, and handle them here.
// is this possible? how can i do this?
});
我希望当客户端 socket.io 代码接收到任何/所有事件时调用此回调函数。
这可能吗?怎么办?
最佳答案
socket.io-client 1.3.7的更新解决方案
var onevent = socket.onevent;
socket.onevent = function (packet) {
var args = packet.data || [];
onevent.call (this, packet); // original call
packet.data = ["*"].concat(args);
onevent.call(this, packet); // additional call to catch-all
};
像这样使用:
socket.on("*",function(event,data) {
console.log(event);
console.log(data);
});
虽然 Mathias Hopf 和 Maros Pixel 的答案很接近,但没有一个答案对我有用,这是我调整后的版本。
注意:这仅捕获自定义事件,而不是连接/断开连接等
关于javascript - Socket.io客户端: respond to all events with one handler?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29247061/