2020-04-21 00:56:39 +05:30
|
|
|
export class EventEmitter {
|
2019-06-27 02:01:36 +05:30
|
|
|
constructor() {
|
|
|
|
this._handlersByName = {};
|
|
|
|
}
|
2019-02-11 01:55:29 +05:30
|
|
|
|
2019-06-27 02:01:36 +05:30
|
|
|
emit(name, ...values) {
|
|
|
|
const handlers = this._handlersByName[name];
|
|
|
|
if (handlers) {
|
|
|
|
for(const h of handlers) {
|
|
|
|
h(...values);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-02-11 01:55:29 +05:30
|
|
|
|
2020-05-07 03:14:52 +05:30
|
|
|
disposableOn(name, callback) {
|
|
|
|
this.on(name, callback);
|
|
|
|
return () => {
|
|
|
|
this.off(name, callback);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-27 02:01:36 +05:30
|
|
|
on(name, callback) {
|
|
|
|
let handlers = this._handlersByName[name];
|
|
|
|
if (!handlers) {
|
2019-06-16 14:24:16 +05:30
|
|
|
this.onFirstSubscriptionAdded(name);
|
2019-06-27 02:01:36 +05:30
|
|
|
this._handlersByName[name] = handlers = new Set();
|
|
|
|
}
|
|
|
|
handlers.add(callback);
|
|
|
|
}
|
2019-02-11 01:55:29 +05:30
|
|
|
|
2019-06-27 02:01:36 +05:30
|
|
|
off(name, callback) {
|
|
|
|
const handlers = this._handlersByName[name];
|
|
|
|
if (handlers) {
|
|
|
|
handlers.delete(callback);
|
|
|
|
if (handlers.length === 0) {
|
|
|
|
delete this._handlersByName[name];
|
2019-06-16 14:24:16 +05:30
|
|
|
this.onLastSubscriptionRemoved(name);
|
2019-06-27 02:01:36 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-06-16 14:24:16 +05:30
|
|
|
|
|
|
|
onFirstSubscriptionAdded(name) {}
|
|
|
|
|
|
|
|
onLastSubscriptionRemoved(name) {}
|
2019-02-11 01:55:29 +05:30
|
|
|
}
|
2020-04-21 01:01:27 +05:30
|
|
|
|
2019-02-11 01:55:29 +05:30
|
|
|
export function tests() {
|
2019-06-27 02:01:36 +05:30
|
|
|
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-11 01:55:29 +05:30
|
|
|
|
2019-06-27 02:01:36 +05:30
|
|
|
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-11 01:55:29 +05:30
|
|
|
|
2019-06-27 02:01:36 +05:30
|
|
|
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-11 01:55:29 +05:30
|
|
|
}
|