Remove `EventEmitter

This commit is contained in:
Aria Minaei 2022-12-01 15:21:00 +01:00
parent 867cf51acb
commit 2bd1dc85a9
2 changed files with 6 additions and 61 deletions

View file

@ -1,6 +1,5 @@
import type {Prism} from './prism/Interface'
import prism from './prism/prism'
import EventEmitter from './utils/EventEmitter'
/**
* Common interface for Box types. Boxes wrap a single value.
@ -39,7 +38,7 @@ export interface IBox<V> {
*/
export default class Box<V> implements IBox<V> {
private _publicPrism: Prism<V>
private _emitter = new EventEmitter()
private _changeListeners = new Set<(newVal: V) => void>()
/**
* @param _value - The initial value of the Box.
@ -51,8 +50,8 @@ export default class Box<V> implements IBox<V> {
protected _value: V,
) {
const subscribe = (listener: (val: V) => void) => {
this._emitter.addEventListener('change', listener)
return () => this._emitter.removeEventListener('change', listener)
this._changeListeners.add(listener)
return () => this._changeListeners.delete(listener)
}
const getValue = () => this._value
@ -69,7 +68,9 @@ export default class Box<V> implements IBox<V> {
set(v: V) {
if (v === this._value) return
this._value = v
this._emitter.emit('change', v)
this._changeListeners.forEach((listener) => {
listener(v)
})
}
/**

View file

@ -1,56 +0,0 @@
import forEach from 'lodash-es/forEach'
import without from 'lodash-es/without'
import type {$FixMe} from '../types'
type Listener = (v: $FixMe) => void
/**
* A simple barebones event emitter
*/
export default class EventEmitter {
_listenersByType: {[eventName: string]: Array<Listener>}
constructor() {
this._listenersByType = {}
}
addEventListener(eventName: string, listener: Listener) {
const listeners =
this._listenersByType[eventName] ||
(this._listenersByType[eventName] = [])
listeners.push(listener)
return this
}
removeEventListener(eventName: string, listener: Listener) {
const listeners = this._listenersByType[eventName]
if (listeners) {
const newListeners = without(listeners, listener)
if (newListeners.length === 0) {
delete this._listenersByType[eventName]
} else {
this._listenersByType[eventName] = newListeners
}
}
return this
}
emit(eventName: string, payload: unknown) {
const listeners = this.getListenersFor(eventName)
if (listeners) {
forEach(listeners, (listener) => {
listener(payload)
})
}
}
getListenersFor(eventName: string) {
return this._listenersByType[eventName]
}
hasListenersFor(eventName: string) {
return this.getListenersFor(eventName) ? true : false
}
}