You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

# OpenSCD Core should make use of a central event-bus

Date: 2023-06-05

## Status

Open

## Context
If we want plugins for OpenSCD to be asynchronous accessible to each other, OpenSCD Core should make use of a central event-bus.
Instead of dispatching an event on the plugin itself, the plugin can dispatch an event on the central event-bus.

HTML Events are only going up in the domtree, not down and/or to siblings.
We can solve this by creating a central event-bus that will be passed down to each plugin.

```ts
export  class EventBus implements EventTarget {

    private  _eventListeners: Map<string, EventListenerOrEventListenerObject[]>;

    constructor() {
        this._eventListeners = new  Map<string, EventListenerOrEventListenerObject[]>();
    }

    addEventListener(type: string, callback: EventListenerOrEventListenerObject): void {
        if (!this._eventListeners.has(type)) {
            this._eventListeners.set(type, []);
        }

        this._eventListeners.get(type)!.push(callback);
    }
    
    dispatchEvent(event: Event): boolean {
        if (this._eventListeners.has(event.type)) {
            this._eventListeners
                .get(event.type)
                !.forEach((cb) =>
                    typeof  cb === 'function' ? cb(event) : cb.handleEvent(event)
                );

            return  true;
        }

        return  false;
    }

    removeEventListener(type: string, callback: EventListenerOrEventListenerObject): void {
        if (this._eventListeners.has(type)) {
            this._eventListeners.set(type, this._eventListeners.get(type)!.filter((cb) =>  cb !== callback));
        }
    }

}
```

## Decision

T.B.D.


## Consequences
Implementing a central event-bus means that current OSCD plugins need some refactoring to dispatch events to the event-bus instead of dispatching events on itself.

  • No labels