Commit 00eafd6

mo khan <mo@mokhan.ca>
2016-12-02 05:02:02
implement EventAggregator#unsubscribe
1 parent 5520d93
Changed files (2)
app/infrastructure/__tests__/event_aggregator_spec.js
@@ -1,20 +1,20 @@
 import EventAggregator from '../event-aggregator';
 
 describe("EventAggregator", () => {
+  class TestSubscriber {
+    notify(event) {
+      this.called = true;
+      this.calledWith = event;
+    }
+  }
+
   let subject = null;
 
   beforeEach(() => {
     subject = new EventAggregator();
   });
 
-  describe("publish", () => {
-    class TestSubscriber {
-      notify(event) {
-        this.called = true;
-        this.calledWith = event;
-      }
-    }
-
+  describe("#publish", () => {
     it ("publishes the event to all interested subscribers", () => {
       let subscriber = new TestSubscriber();
       subject.subscribe('LOGGED_IN', subscriber);
@@ -33,4 +33,16 @@ describe("EventAggregator", () => {
       expect(subscriber.calledWith).toBeUndefined();
     });
   });
+
+  describe("#unsubscribe", () => {
+    it ("unsubscribes a listener", () => {
+      let subscriber = new TestSubscriber();
+      subject.subscribe('LOGGED_IN', subscriber);
+      subject.unsubscribe(subscriber);
+      subject.publish({ event: 'LOGGED_IN', username: 'blah' })
+
+      expect(subscriber.called).toBeFalsy;
+      expect(subscriber.calledWith).toBeUndefined();
+    });
+  });
 });
app/infrastructure/event-aggregator.js
@@ -1,18 +1,24 @@
-
 export default class EventAggregator {
   constructor() {
     this.subscriptions = { };
   }
 
   subscribe(event, subscriber) {
-    this.subscriptionsFor(event).push(subscriber);
+    this._subscriptionsFor(event).push(subscriber);
   }
 
   publish(event) {
-    this.subscriptionsFor(event.event).forEach(x => x.notify(event));
+    this._subscriptionsFor(event.event).forEach(x => x.notify(event));
+  }
+
+  unsubscribe(subscriber) {
+    for (var event in this.subscriptions) {
+      let items = this._subscriptionsFor(event)
+      items.splice(items.indexOf(subscriber));
+    }
   }
 
-  subscriptionsFor(event) {
+  _subscriptionsFor(event) {
     let key = event;
     if (!this.subscriptions.hasOwnProperty(key)) {
       this.subscriptions[key] = [];