feat: add support for catch-all listeners

Inspired from EventEmitter2 [1]

The API is similar to the one on the server-side:

```js
socket.onAny((event, ...args) => {});

socket.prependAny((event, ...args) => {});

socket.offAny(); // remove all listeners

socket.offAny(listener);

const listeners = socket.listenersAny();
```

[1]: https://github.com/EventEmitter2/EventEmitter2
This commit is contained in:
Damien Arrachequesne
2020-10-26 00:07:53 +01:00
parent 71d60480af
commit 55f464f59e
2 changed files with 120 additions and 2 deletions

View File

@@ -234,4 +234,51 @@ describe("socket", function () {
}, 200);
});
});
describe("onAny", () => {
it("should call listener", (done) => {
const socket = io("/abc");
socket.onAny((event, arg1) => {
expect(event).to.be("handshake");
expect(arg1).to.be.an(Object);
done();
});
});
it("should prepend listener", (done) => {
const socket = io("/abc");
let count = 0;
socket.onAny((event, arg1) => {
expect(count).to.be(2);
done();
});
socket.prependAny(() => {
expect(count++).to.be(1);
});
socket.prependAny(() => {
expect(count++).to.be(0);
});
});
it("should remove listener", (done) => {
const socket = io("/abc");
let count = 0;
const fail = () => done(new Error("fail"));
socket.onAny(fail);
socket.offAny(fail);
expect(socket.listenersAny.length).to.be(0);
socket.onAny(() => {
done();
});
});
});
});