Skip to content

Commit

Permalink
Added once helper to EventEmitter
Browse files Browse the repository at this point in the history
  • Loading branch information
FlorianRappl committed Oct 20, 2023
1 parent 8fa3c6d commit 3ce7216
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 6 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
1 change: 1 addition & 0 deletions src/framework/piral-base/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
23 changes: 17 additions & 6 deletions src/framework/piral-base/src/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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;
},
};
Expand Down
6 changes: 6 additions & 0 deletions src/framework/piral-base/src/types/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ export interface EventEmitter {
* @param callback The callback to trigger.
*/
on<K extends keyof PiralEventMap>(type: K, callback: Listener<PiralEventMap[K]>): 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<K extends keyof PiralEventMap>(type: K, callback: Listener<PiralEventMap[K]>): EventEmitter;
/**
* Detaches an existing event listener.
* @param type The type of the event to listen for.
Expand Down

0 comments on commit 3ce7216

Please sign in to comment.