2020-04-20 21:26:39 +02:00
|
|
|
export class EventEmitter {
|
2019-06-26 22:31:36 +02:00
|
|
|
constructor() {
|
|
|
|
this._handlersByName = {};
|
|
|
|
}
|
2019-02-10 21:25:29 +01:00
|
|
|
|
2019-06-26 22:31:36 +02:00
|
|
|
emit(name, ...values) {
|
|
|
|
const handlers = this._handlersByName[name];
|
|
|
|
if (handlers) {
|
|
|
|
for(const h of handlers) {
|
|
|
|
h(...values);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-02-10 21:25:29 +01:00
|
|
|
|
2019-06-26 22:31:36 +02:00
|
|
|
on(name, callback) {
|
|
|
|
let handlers = this._handlersByName[name];
|
|
|
|
if (!handlers) {
|
2019-06-16 10:54:16 +02:00
|
|
|
this.onFirstSubscriptionAdded(name);
|
2019-06-26 22:31:36 +02:00
|
|
|
this._handlersByName[name] = handlers = new Set();
|
|
|
|
}
|
|
|
|
handlers.add(callback);
|
|
|
|
}
|
2019-02-10 21:25:29 +01:00
|
|
|
|
2019-06-26 22:31:36 +02:00
|
|
|
off(name, callback) {
|
|
|
|
const handlers = this._handlersByName[name];
|
|
|
|
if (handlers) {
|
|
|
|
handlers.delete(callback);
|
|
|
|
if (handlers.length === 0) {
|
|
|
|
delete this._handlersByName[name];
|
2019-06-16 10:54:16 +02:00
|
|
|
this.onLastSubscriptionRemoved(name);
|
2019-06-26 22:31:36 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-06-16 10:54:16 +02:00
|
|
|
|
|
|
|
onFirstSubscriptionAdded(name) {}
|
|
|
|
|
|
|
|
onLastSubscriptionRemoved(name) {}
|
2019-02-10 21:25:29 +01:00
|
|
|
}
|
|
|
|
//#ifdef TESTS
|
|
|
|
export function tests() {
|
2019-06-26 22:31:36 +02:00
|
|
|
return {
|
|
|
|
test_on_off(assert) {
|
|
|
|
let counter = 0;
|
|
|
|
const e = new EventEmitter();
|
|
|
|
const callback = () => counter += 1;
|
|
|
|
e.on("change", callback);
|
|
|
|
e.emit("change");
|
|
|
|
e.off("change", callback);
|
|
|
|
e.emit("change");
|
|
|
|
assert.equal(counter, 1);
|
|
|
|
},
|
2019-02-10 21:25:29 +01:00
|
|
|
|
2019-06-26 22:31:36 +02:00
|
|
|
test_emit_value(assert) {
|
|
|
|
let value = 0;
|
|
|
|
const e = new EventEmitter();
|
|
|
|
const callback = (v) => value = v;
|
|
|
|
e.on("change", callback);
|
|
|
|
e.emit("change", 5);
|
|
|
|
e.off("change", callback);
|
|
|
|
assert.equal(value, 5);
|
|
|
|
},
|
2019-02-10 21:25:29 +01:00
|
|
|
|
2019-06-26 22:31:36 +02:00
|
|
|
test_double_on(assert) {
|
|
|
|
let counter = 0;
|
|
|
|
const e = new EventEmitter();
|
|
|
|
const callback = () => counter += 1;
|
|
|
|
e.on("change", callback);
|
|
|
|
e.on("change", callback);
|
|
|
|
e.emit("change");
|
|
|
|
e.off("change", callback);
|
|
|
|
assert.equal(counter, 1);
|
|
|
|
}
|
|
|
|
};
|
2019-02-10 21:25:29 +01:00
|
|
|
}
|
2019-06-16 10:54:16 +02:00
|
|
|
//#endif
|