Skip to content

Commit

Permalink
Do not use this in event emitters.
Browse files Browse the repository at this point in the history
  • Loading branch information
manuelroemer committed Jan 17, 2024
1 parent c8909fb commit 029b6d7
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 10 deletions.
8 changes: 4 additions & 4 deletions src/framework/piral-base/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import type { PiletMetadata, EventEmitter, PiletApi, PiletApiExtender } from './

export function initializeApi(target: PiletMetadata, events: EventEmitter): PiletApi {
return {
on: events.on.bind(events),
once: events.once.bind(events),
off: events.off.bind(events),
emit: events.emit.bind(events),
on: events.on,
once: events.once,
off: events.off,
emit: events.emit,
meta: Object.assign({}, target),
};
}
Expand Down
14 changes: 8 additions & 6 deletions src/framework/piral-base/src/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,19 @@ function nameOf(type: string | number) {
export function createListener(state: any = {}): EventEmitter {
const eventListeners: EventListeners = [];

return {
const events = {
on(type, callback) {
const listener = ({ detail }: CustomEvent) => detail && detail.state === state && callback(detail.arg);
document.body.addEventListener(nameOf(type), listener);
eventListeners.push([callback, listener]);
return this;
return events;
},
once(type, callback) {
const cb = (ev: any) => {
this.off(type, cb);
events.off(type, cb);
callback(ev);
};
return this.on(type, cb);
return events.on(type, cb);
},
off(type, callback) {
const [listener] = eventListeners.filter((m) => m[0] === callback);
Expand All @@ -37,7 +37,7 @@ export function createListener(state: any = {}): EventEmitter {
eventListeners.splice(eventListeners.indexOf(listener), 1);
}

return this;
return events;
},
emit(type, arg) {
document.body.dispatchEvent(
Expand All @@ -50,7 +50,9 @@ export function createListener(state: any = {}): EventEmitter {
},
}),
);
return this;
return events;
},
};

return events;
}

0 comments on commit 029b6d7

Please sign in to comment.