Skip to content

Commit 5fb2c12

Browse files
committed
Add registry in callback before publish
1 parent 8e626aa commit 5fb2c12

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

src/Event.js

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,10 @@ const subscribe = (type, callback) => {
1111
subscriptions[type] = {};
1212
}
1313

14-
subscriptions[type][id] = callback;
15-
16-
let last = messages.get(type);
17-
1814
const registry = {
1915
id,
2016
type,
17+
callback,
2118
unsubscribe: () => {
2219
console.debug("react-event", "unsubscribe", type, id);
2320
delete subscriptions[type][id];
@@ -28,6 +25,10 @@ const subscribe = (type, callback) => {
2825
},
2926
};
3027

28+
subscriptions[type][id] = registry;
29+
30+
let last = messages.get(type);
31+
3132
if (last) {
3233
callback(last, registry);
3334
}
@@ -40,8 +41,10 @@ const publish = (type, payload) => {
4041
messages.set(type, payload);
4142

4243
Object.keys(subscriptions[type] || {}).forEach((key) => {
44+
const registry = subscriptions[type][key];
45+
4346
setTimeout(() => {
44-
subscriptions[type][key](payload);
47+
registry.callback(payload, registry);
4548
}, 0);
4649
});
4750
};

src/test/event.test.js

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,17 +61,35 @@ describe("react-event", () => {
6161
expect(lastPublishedEvent).toEqual({ data: "test payload" });
6262
});
6363

64-
it("returns registry in callback", () => {
64+
it("returns registry in callback", (done) => {
6565
publish("CALLBACK_REGISTRY_EVENT", { data: "test payload" });
6666

6767
subscribe("CALLBACK_REGISTRY_EVENT", (result, registry) => {
68+
expect(result).toMatchObject({ data: "test payload" });
6869
expect(registry).toMatchObject({
6970
id: expect.any(String),
7071
type: "CALLBACK_REGISTRY_EVENT",
72+
callback: expect.any(Function),
7173
unsubscribe: expect.any(Function),
7274
});
7375

7476
registry.unsubscribe();
7577
});
78+
79+
subscribe("CALLBACK_REGISTRY_EVENT_2", (result, registry) => {
80+
expect(result).toMatchObject({ data: "test payload 2" });
81+
expect(registry).toMatchObject({
82+
id: expect.any(String),
83+
type: "CALLBACK_REGISTRY_EVENT_2",
84+
callback: expect.any(Function),
85+
unsubscribe: expect.any(Function),
86+
});
87+
88+
registry.unsubscribe();
89+
90+
done();
91+
});
92+
93+
publish("CALLBACK_REGISTRY_EVENT_2", { data: "test payload 2" });
7694
});
7795
});

0 commit comments

Comments
 (0)