vector-im-hydrogen-web/src/EventEmitter.js

76 lines
2.0 KiB
JavaScript
Raw Normal View History

2019-02-10 21:25:29 +01:00
export default 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) {
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];
this.onLastSubscriptionRemoved(name);
2019-06-26 22:31:36 +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
}
//#endif