Skip to content

Commit

Permalink
feat(all): subscribe methods now return subscription object with disp…
Browse files Browse the repository at this point in the history
…ose method

BREAKING CHANGE - Fixes #10 Subscribe methods now return a Subscription
object which as a dispose method on it for unsubscribing. This matches
the pattern we are using in the new public binding api and we will use
this for any/all consumer facing eventing apis going forward. This also
matches the Rx pattern.
  • Loading branch information
EisenbergEffect committed Oct 13, 2015
1 parent 182eb86 commit 862cb83
Show file tree
Hide file tree
Showing 2 changed files with 106 additions and 119 deletions.
42 changes: 21 additions & 21 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ class Handler {
}
}

interface Subscription {
dispose(): void;
}

export class EventAggregator {
constructor() {
this.eventLookup = {};
Expand All @@ -35,7 +39,7 @@ export class EventAggregator {
while (i--) {
subscribers[i](data, event);
}
} catch(e) {
} catch (e) {
logger.error(e);
}
}
Expand All @@ -47,43 +51,39 @@ export class EventAggregator {
while (i--) {
subscribers[i].handle(event);
}
} catch(e) {
} catch (e) {
logger.error(e);
}
}
}

subscribe(event: string | Function, callback: Function): Function {
let subscribers;
subscribe(event: string | Function, callback: Function): Subscription {
let handler;
let subscribers;

if (typeof event === 'string') {
handler = callback;
subscribers = this.eventLookup[event] || (this.eventLookup[event] = []);
subscribers.push(callback);

return function() {
let idx = subscribers.indexOf(callback);
if (idx !== -1) {
subscribers.splice(idx, 1);
}
};
} else {
handler = new Handler(event, callback);
subscribers = this.messageHandlers;
}

handler = new Handler(event, callback);
subscribers = this.messageHandlers;
subscribers.push(handler);

return function() {
let idx = subscribers.indexOf(handler);
if (idx !== -1) {
subscribers.splice(idx, 1);
return {
dispose() {
let idx = subscribers.indexOf(handler);
if (idx !== -1) {
subscribers.splice(idx, 1);
}
}
};
}

subscribeOnce(event: string | Function, callback: Function): Function {
let sub = this.subscribe(event, function(a, b) {
sub();
subscribeOnce(event: string | Function, callback: Function): Subscription {
let sub = this.subscribe(event, (a, b) => {
sub.dispose();
return callback(a, b);
});

Expand Down
Loading

0 comments on commit 862cb83

Please sign in to comment.