Commit c706c12
Changed files (2)
app
infrastructure
__tests__
app/infrastructure/__tests__/event_aggregator_spec.js
@@ -17,11 +17,15 @@ describe("EventAggregator", () => {
describe("#publish", () => {
it ("publishes the event to all interested subscribers", () => {
let subscriber = new TestSubscriber();
+ let otherSubscriber = new TestSubscriber();
subject.subscribe('LOGGED_IN', subscriber);
+ subject.subscribe('LOGGED_IN', otherSubscriber);
subject.publish({ event: 'LOGGED_IN', username: 'blah' })
expect(subscriber.called).toBeTruthy();
expect(subscriber.calledWith.username).toEqual('blah');
+ expect(otherSubscriber.called).toBeTruthy();
+ expect(otherSubscriber.calledWith.username).toEqual('blah');
});
it ("does not publish events to subscribers interested in other events", function() {
@@ -37,12 +41,19 @@ describe("EventAggregator", () => {
describe("#unsubscribe", () => {
it ("unsubscribes a listener", () => {
let subscriber = new TestSubscriber();
+ let otherSubscriber = new TestSubscriber();
subject.subscribe('LOGGED_IN', subscriber);
+ subject.subscribe('LOGGED_IN', otherSubscriber);
+
subject.unsubscribe(subscriber);
+
subject.publish({ event: 'LOGGED_IN', username: 'blah' })
- expect(subscriber.called).toBeFalsy;
+ expect(subscriber.called).toBeFalsy();
expect(subscriber.calledWith).toBeUndefined();
+
+ expect(otherSubscriber.called).toBeTruthy();
+ expect(otherSubscriber.calledWith).toBeTruthy();
});
});
});
app/infrastructure/event-aggregator.js
@@ -4,13 +4,13 @@ export default class EventAggregator {
}
subscribe(event, subscriber) {
- this._subscriptionsFor(event).push(subscriber);
+ this._subscriptionsFor(event).add(subscriber);
}
publish(event) {
+ console.log("publishing:");
+ console.dir(event);
this._subscriptionsFor(event.event).forEach((x) => {
- console.log("publishing:");
- console.dir(event);
console.dir(x);
x.notify(event);
});
@@ -19,14 +19,16 @@ export default class EventAggregator {
unsubscribe(subscriber) {
for (var event in this.subscriptions) {
let items = this._subscriptionsFor(event)
- items.splice(items.indexOf(subscriber));
+ if (items.has(subscriber)) {
+ items.delete(subscriber);
+ }
}
}
_subscriptionsFor(event) {
let key = event;
if (!this.subscriptions.hasOwnProperty(key)) {
- this.subscriptions[key] = [];
+ this.subscriptions[key] = new Set();
}
return this.subscriptions[key];
}