Skip to content

Commit

Permalink
event.once
Browse files Browse the repository at this point in the history
  • Loading branch information
joaomoreno committed Aug 23, 2016
1 parent 48bc670 commit 8e4b3e0
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/vs/base/common/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,17 @@ export function fromPromise<T>(promise: TPromise<Event<T>>): Event<T> {
return emitter.event;
}

export function once<T>(event: Event<T>): Event<T> {
return (listener, thisArgs = null, disposables?) => {
const result = event(e => {
result.dispose();
return listener.call(thisArgs, e);
}, null, disposables);

return result;
};
}

export function mapEvent<I,O>(event: Event<I>, map: (i:I)=>O): Event<O> {
return (listener, thisArgs = null, disposables?) => event(i => listener.call(thisArgs, map(i)), null, disposables);
}
Expand Down
30 changes: 29 additions & 1 deletion src/vs/base/test/common/event.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
'use strict';

import * as assert from 'assert';
import Event, {Emitter, fromEventEmitter, debounceEvent, EventBufferer} from 'vs/base/common/event';
import Event, {Emitter, fromEventEmitter, debounceEvent, EventBufferer, once} from 'vs/base/common/event';
import {IDisposable} from 'vs/base/common/lifecycle';
import {EventEmitter} from 'vs/base/common/eventEmitter';
import Errors = require('vs/base/common/errors');
Expand Down Expand Up @@ -254,4 +254,32 @@ suite('EventBufferer', () => {

listener.dispose();
});

test('once', () => {
const emitter = new Emitter<void>();

let counter1 = 0, counter2 = 0, counter3 = 0;

const listener1 = emitter.event(() => counter1++);
const listener2 = once(emitter.event)(() => counter2++);
const listener3 = once(emitter.event)(() => counter3++);

assert.equal(counter1, 0);
assert.equal(counter2, 0);
assert.equal(counter3, 0);

listener3.dispose();
emitter.fire();
assert.equal(counter1, 1);
assert.equal(counter2, 1);
assert.equal(counter3, 0);

emitter.fire();
assert.equal(counter1, 2);
assert.equal(counter2, 1);
assert.equal(counter3, 0);

listener1.dispose();
listener2.dispose();
});
});

0 comments on commit 8e4b3e0

Please sign in to comment.