npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

weak-event

v2.0.5

Published

C#-Style Typescript Events/Weak Events

Downloads

2,596

Readme

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:

  • https://v8.dev/features/weak-references
  • https://docs.microsoft.com/en-us/dotnet/desktop/wpf/advanced/weak-event-patterns

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