Nimoy Prospers Mystically

    weak-event
    TypeScript icon, indicating that this package has built-in type declarations

    2.0.5 • Public • Published

    weak-event

    C#-Style Typescript Events/Weak Events

    weak-event Package Version Node Version Coverage Status License

    Javascript's event are somewhat awkward to use and lack first-class typing support or a native 'weak event' implementation. This package seeks to allow for lightweight, zero dependency, easy to use C#-style events that work on NodeJS and modern browsers

    Note:

    Weak events carry a measurable overhead over conventional events. Be wary of this in performance-critical applications.

    The package is quite similar to strongly-typed-events (a.k.a ts-events) but is significantly smaller and less featured.

    The main focus however, is support for modern weak events that require NodeJS >= 14.6 or an updated, modern browser due to the use of FinalizationRegistry

    Weak events are useful when object life-cycles cannot be guaranteed or controlled. This tends to happen in collaborative/enterprise scenarios where several developers may create or consume events or entities without fully understanding their life-cycles and exceptional conditions or the code's ecosystem. Usage of weak references in such cases may help prevent hard to detect event handler leaks which are some of the most common causes of slow memory leaks.

    Installation

    npm install weak-event or yarn install weak-event

    Please note that this package is unbundled

    Efficiency

    Estimated efficiency values of package code.

    Note that ECMA does not specify any complexity constraints for array functions so actual complexity may vary.

    Function Average Time Average Space
    ITypedEvent.attach O(1) O(1)
    ITypedEvent.detach O(n) O(1)
    ITypedEvent.invoke O(n) O(1)
    ITypedEvent.invokeAsync O(n) O(n)

    Other notes

    For any bugs, questions or suggestions or comments, feel free to hit me on my mail at yuval.pomer

    Feedback, positive or otherwise is appreciated.

    For more reading material regarding the necessity and/or potential use-cases of the 'Weak Event' pattern in general, please refer to:

    Usage

    Weak Event

    The below example is a simplified but rather typical use-case where an event listener object goes out of scope.

    Under normal circumstances, the Garbage Collector would not reclaim the object as it's still referenced by the the event source's listener's dictionary.

    Using WeakEvent, however, GC can collect the object, at which point a finalizer will be invoked and the dead reference cleaned from the event source's map. This ensures memory is eventually reclaimed and can, over time, make a significant difference.

    import { TypedEvent, ITypedEvent } from 'weak-event';
    
    class DummyEventSource {
    
    	private _someEvent = new WeakEvent<DummyEventSource, boolean>();
    
    	public get someEvent(): ITypedEvent<DummyEventSource, boolean> {
    		return this._someEvent;
    	}
    
    	private async raiseEventAsynchronously(): Promise<void> {
    		this._someEvent.invokeAsync(this, true);
    	}
    }
    
    class DummyEventConsumer {
    
    	public constructor(eventSource: DummyEventSource) {
    
    		// Valid usage. Handler signature matches event.
    		eventSource.someEvent.attach(this.onEvent);
    	}
    
    	private onEvent(sender: DummyEventSource, e: boolean): void {
    		console.log(`Event payload: ${e}`);
    	}
    }
    
    class LeakyClass {
    
    	private _eventSource = new DummyEventSource();
    
    	public createConsumer(): void {
    		const consumer = new DummyEventConsumer(this._eventSource);
    		/* Do something with consumer
    		 ...
    		 ...
    		 ...
    		 Forget to 'dispose'. Consumer goes out of scope. Memory is leaked
    		*/
    	}
    }

    Typed Event

    The most basic type of event. Uses strong references and behaves like other events do

    import { TypedEvent, ITypedEvent } from 'weak-event';
    
    class DummyEventSource {
    
    	public get someProperty(): string {
    		return "I'm an event source";
    	}
    
    	private _someEvent = new TypedEvent<DummyEventSource, string>();
    
    	public get someEvent(): ITypedEvent<DummyEventSource, string> {
    		return this._someEvent;
    	}
    
    	private raiseEventSynchronously(): void {
    		this._someEvent.invoke(this, 'Some value');
    
    		// We get here after all events have been synchronously invoked
    		console.log('Done!');
    	}
    
    	private async raiseEventAsynchronously(): Promise<void> {
    		this._someEvent.invokeAsync(this, 'Some value');
    
    		// We get here as soon as the 'invokeAsync' method yields.
    		// Events are invoked asynchronously.
    		console.log('Done!');
    	}
    }
    
    class DummyEventConsumer {
    
    	private _eventSource: DummyEventSource;
    
    	public constructor(eventSource: DummyEventSource) {
    
    		this._eventSource = eventSource;
    
    		// Valid usage. Handler signature matches event.
    		eventSource.someEvent.attach(this.onEvent);
    	}
    
    	private onEvent(sender: DummyEventSource, e: string): void {
    		console.log(`Caller property: ${sender.someProperty}, Event payload: ${e}`);
    	}
    
    	public dispose(): void {
    		// Detach the event handler
    		this._eventSource.someEvent.detach(this.onEvent);
    	}
    }
    

    Changelog

    Changelog may be found at the project's GitHub here

    Install

    npm i weak-event

    DownloadsWeekly Downloads

    14

    Version

    2.0.5

    License

    ISC

    Unpacked Size

    44.3 kB

    Total Files

    30

    Last publish

    Collaborators

    • yuval.pomer