"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * A service for sending events outside DOM.
 */
class CustomEventService {
    constructor() {
        this.eventListeners = {};
    }
    add(id, eventName, fn) {
        if (!this.eventListeners[eventName])
            this.eventListeners[eventName] = {};
        if (!this.eventListeners[eventName][id])
            this.eventListeners[eventName][id] = [];
        this.eventListeners[eventName][id].push(fn);
    }
    remove(id, eventName, fn) {
        this.eventListeners[eventName][id] = this.eventListeners[eventName][id].filter(_fn => _fn !== fn);
    }
    send(id, eventName, data, callback, { bubble = true } = {}) {
        const ids = Object.keys(this.eventListeners[eventName] || {}).filter(_id => id.startsWith(_id)).sort().reverse();
        outer: for (let _id of ids) {
            for (let listener of this.eventListeners[eventName][_id]) {
                const result = listener(data, callback);
                if (!bubble)
                    break outer;
                if (result === true || result === undefined) {
                    return;
                }
            }
        }
        callback && callback();
    }
}
exports.default = CustomEventService;
