From 3ce7216db249e07832c0ac46fcd50e71d3287d13 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Fri, 20 Oct 2023 14:14:22 +0200 Subject: [PATCH] Added `once` helper to EventEmitter --- CHANGELOG.md | 4 ++++ src/framework/piral-base/src/api.ts | 1 + src/framework/piral-base/src/events.ts | 23 +++++++++++++++++------ src/framework/piral-base/src/types/api.ts | 6 ++++++ 4 files changed, 28 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 67acd8e52..75366cb4d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Piral Changelog +## 1.3.2 (tbd) + +- Added `once` as convenience methods to `EventEmitter` + ## 1.3.1 (October 19, 2023) - Updated behavior with unresolved inherited dependencies (#633) diff --git a/src/framework/piral-base/src/api.ts b/src/framework/piral-base/src/api.ts index 8ef5a7e78..40185b87c 100644 --- a/src/framework/piral-base/src/api.ts +++ b/src/framework/piral-base/src/api.ts @@ -4,6 +4,7 @@ import type { PiletMetadata, EventEmitter, PiletApi, PiletApiExtender } from './ export function initializeApi(target: PiletMetadata, events: EventEmitter): PiletApi { return { on: events.on, + once: events.once, off: events.off, emit: events.emit, meta: __assign({}, target), diff --git a/src/framework/piral-base/src/events.ts b/src/framework/piral-base/src/events.ts index 9e240c6a8..5a8324e86 100644 --- a/src/framework/piral-base/src/events.ts +++ b/src/framework/piral-base/src/events.ts @@ -22,6 +22,13 @@ export function createListener(state: any = {}): EventEmitter { eventListeners.push([callback, listener]); return this; }, + once(type, callback) { + const cb = (ev: any) => { + this.off(type, cb); + callback(ev); + }; + return this.on(type, cb); + }, off(type, callback) { const [listener] = eventListeners.filter((m) => m[0] === callback); @@ -33,12 +40,16 @@ export function createListener(state: any = {}): EventEmitter { return this; }, emit(type, arg) { - const ce = document.createEvent('CustomEvent'); - ce.initCustomEvent(nameOf(type), false, false, { - arg, - state, - }); - document.body.dispatchEvent(ce); + document.body.dispatchEvent( + new CustomEvent(nameOf(type), { + bubbles: false, + cancelable: false, + detail: { + arg, + state, + }, + }), + ); return this; }, }; diff --git a/src/framework/piral-base/src/types/api.ts b/src/framework/piral-base/src/types/api.ts index c061a730b..a8c8ba3c5 100644 --- a/src/framework/piral-base/src/types/api.ts +++ b/src/framework/piral-base/src/types/api.ts @@ -36,6 +36,12 @@ export interface EventEmitter { * @param callback The callback to trigger. */ on(type: K, callback: Listener): EventEmitter; + /** + * Attaches a new event listener that is removed once the event fired. + * @param type The type of the event to listen for. + * @param callback The callback to trigger. + */ + once(type: K, callback: Listener): EventEmitter; /** * Detaches an existing event listener. * @param type The type of the event to listen for.