Skip to content

Commit

Permalink
Add once method to Event Dispatcher
Browse files Browse the repository at this point in the history
  • Loading branch information
MatthewCallis committed Oct 12, 2019
1 parent dd09926 commit 92de2f9
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/event-dispatcher.js
Expand Up @@ -123,6 +123,24 @@ class EventDispatcher {
event.register(callback);
}

/**
* Add a function to an event that will be called only once when the label is dispatched.
* Uses the `EventDispatcher.on` method with a function wrapped to call off on use.
* @param {String} label - The human readable identifier of the event.
* @param {Function} callback - Function to be called when the event is fired.
* @example
* bus.once('one-time-process', callback);
* @memberof EventDispatcher
*/
once(label, callback) {
debug('once:', label, callback);
const cb = (...args) => {
this.off(label, cb);
callback.apply(this, args);
};
this.on(label, cb);
}

/**
* Remove a function from an event.
* @param {String} label - The human readable identifier of the event.
Expand Down
11 changes: 11 additions & 0 deletions test/event-dispatcher.test.js
Expand Up @@ -183,6 +183,17 @@ test('#on(label, callback): adds callbacks to the given event', (t) => {
t.is(Object.keys(ed.events).length, 1);
});

test('#once(label, callback): adds callbacks to the given event', async (t) => {
const ed = new EventDispatcher();
t.is(Object.keys(ed.events).length, 0);
ed.once('test', a);
t.is(Object.keys(ed.events).length, 1);
ed.once('test', b);
t.is(Object.keys(ed.events).length, 1);
await ed.dispatch('test', b);
t.is(Object.keys(ed.events).length, 0);
});

test('#on(label, callback): throws an error with invalid label or callback', (t) => {
const ed = new EventDispatcher();
t.throws(() => { ed.on('', a); });
Expand Down

0 comments on commit 92de2f9

Please sign in to comment.