4.9.83 • Published 10 months ago

@taktikorg/tempore-quis-temporibus v4.9.83

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

Unify Emitter

Unify Emitter is a lightweight event emitter package that provides a simple and unified API for managing and emitting events. It works seamlessly in both Node.js and browser environments, allowing easy communication between components, modules, or different parts of your application.

npm version License: MIT

Features

  • Cross-Platform: Works in both Node.js and browser environments.
  • Simple API: Provides a straightforward and intuitive API for event handling.

  • Lightweight: Aims to be lightweight and minimal, without unnecessary dependencies.

  • TypeScript Support: Built with TypeScript and includes type definitions.

Installation

You can install Unify Emitter via npm:

npm install @taktikorg/tempore-quis-temporibus

Usage

Here's a basic example demonstrating how to use Unify Emitter:

// Import the createUnifyEmitter class
import UnifyEmitter from "@taktikorg/tempore-quis-temporibus";

// Create an instance of UnifyEmitter
const emitter = new UnifyEmitter<{
  myEvent: string;
}>();

// Subscribe to the 'myEvent' event
emitter.on("myEvent", (data) => {
  console.log("Event emitted:", data);
});

// Emit the 'myEvent' event
emitter.emit("myEvent", "Hello, world!"); // Output: `Event emitted: Hello, world!`
emitter.emit("myEvent", "Hello, world!"); // Output: `Event emitted: Hello, world!`
emitter.emit("myEvent", "Hello, world!"); // Output: `Event emitted: Hello, world!`

Inheritance

In certain situations, you may encounter a scenario where you need to inherit a class that already extends UnifyEmitter. The API provides a simple technique to achieve inheritance from classes that already extend UnifyEmitter using generics.

Here is a basic example that demonstrates this concept:

import UnifyEmitter, { EventsObject } from "@taktikorg/tempore-quis-temporibus";

// Define the events specific to the entity
interface EntityEvents {
  move: {
    /**
     * The entity's position on the y-axis.
     */
    x: number;
    /**
     * The entity's position on the x-axis.
     */
    y: number;
  };
}

// Define the events specific to the player
type PlayerEvents = EventsObject<
  EntityEvents,
  {
    punch: {
      /**
       * The direction of the player's punch represented in a 3D coordinate system (x, y, z).
       * The values represent the direction along each axis.
       */
      direction: [number, number, number];
      /**
       * The strength or force of the punch.
       */
      force: number;
    };
  }
>;

// Create a generic class that extends UnifyEmitter and incorporates the EntityEvents
class Entity<T extends EntityEvents> extends UnifyEmitter<T> {
  constructor() {
    super();

    this.emit("move", {
      x: 0,
      y: 5,
    });
  }
}

// Create a specific class for the player that extends the Entity class and incorporates the PlayerEvents
class Player extends Entity<PlayerEvents> {}

// Instantiate an instance of the Entity class
const entity = new Entity();

// Instantiate an instance of the Player class
const player = new Player();

// Emit a "move" event on the entity with the provided coordinates (x: 5, y: 5)
entity.emit("move", { x: 5, y: 5 }); // Works fine!

// Emit a "move" event on the player with the provided coordinates (x: 5, y: 5)
player.emit("move", { x: 5, y: 5 }); // Works fine!

// Emit a "punch" event on the player with the provided direction and force
player.emit("punch", {
  direction: [0, 1, 0],
  force: 3,
}); // Works fine!

// The following line will result in a compile-time error (not runtime). Please keep that in mind.
// entity.emit("punch", {
//   direction: [0, 1, 0],
//   force: 3,
// });

Examples

This repository includes examples showcasing the usage of the UnifyEmitter package. You can find these examples in the examples folder.

API

on(event: E, listener: Callback<ExtractEvent<T>>): typeof listener

Subscribes to an event.

  • event (required): The event to subscribe to.
  • listener (required): The event listener callback.
  • Returns: The provided listener.

once(event: E, listener: Callback<ExtractEvent<T>>): void

Subscribes to an event once. The listener will be automatically unsubscribed after it's called.

  • event (required): The event to subscribe to.
  • listener (required): The event listener callback.

off(event: E, listener: Callback<ExtractEvent<T>>): void

Unsubscribes from an event.

  • event (required): The event to unsubscribe from.
  • listener (required): The event listener callback to remove.

emit(event: E, data: ExtractEvent<T>, doCopy?: boolean): void

Emits an event.

  • event (required): The event to emit.
  • data (required): The data to pass to the event listeners.
  • doCopy (optional): Whether to perform a shallow copy of the data before passing it to the listeners.

listeners(event: E): Callback<ExtractEvent<T>>[]

Retrieves an array of all listeners subscribed to a specific event.

  • event (required): The event to retrieve listeners for.
  • Returns: An array of listeners for the specified event.

listenerCount(event: E): number

Retrieves the number of listeners subscribed to a specific event.

  • event (required): The event to count listeners for.
  • Returns: The number of listeners for the specified event.

prependOn(event: E, listener: Callback<ExtractEvent<T>>): typeof listener

Subscribes to an event and adds the listener to the beginning of the listeners array.

  • event (required): The event to subscribe to.
  • listener (required): The event listener callback.
  • Returns: The provided listener.

removeAllListeners(event?: E): void

Removes all listeners for a specific event or for all events.

  • event (optional): The event to remove listeners for. If not provided, all listeners for all events will be removed.

Contributing

Contributions are welcome! If you find any issues or have suggestions for improvements, feel free to open an issue or submit a pull request in the GitHub repository.

License

This project is licensed under the MIT License. See the MIT LICENSE

core-jsassignpreserve-symlinksbrowserlistoptimistdependency managerhookformstableamazoncurriedstringifymapreduceunicodeparsetyped arrayfilecharactertrimroute53eslintconfigelectrontestercolumnstypanionsigtermsymboldeterministicjwteventEmittercallbindclassnamesinternal slotconfigpropertieses6gesturescollection.es6fast-deep-cloneintrinsicoutputTypeBoxES2020toSortedtakeapolloUnderscorejapanesegradients csscloudfrontreducerawesomesauceviewArray.prototype.flatglobalbytePushsignedCSSStyleDeclarationglobes7signalsforkarrayparser.gitignoreintacitquoteWebSocketObject.getPrototypeOfECMAScript 2016definefast-deep-copyObservablescircularcolumnajaxReactiveExtensionsES2022mergecompile lessreact-testing-libraryBigInt64Arrayloadbalancingpasswordcss-in-jsreduxshamtouchjson-schemaposeassertionuninstalltypesflagsconcaturlfast-clonejsxs3StreamsBigUint64Arrayless compilerweakmapstyled-componentsRxJSsafeimportexporteslint-plugintoStringTagless cssregular expressiondeep-copyspinnerssortedES2023binariesECMAScript 2018es2018propmake dirES6bannerYAMLec2east-asian-widthvestqs.envvalidchromiumclasseslanguageinstallerkeyssuperagentsubprocessboundslotdataWeakMapcss variablecopyuser-streamsextendpropertyjoidirasterisksiteration-0httpschainopeencryptiontypescriptpostcssIteratorhandlerszodfromansipredictablerandomcolorSetnested cssrfc9562byteOffsetprefixjson-schema-validatorfindLastIndexreact-componentquerystringString.prototype.trimprivate datafantasy-landbootstrap cssES2016testingECMAScript 2021hashprototypejavascripttypesafeaccessorjshintmodulestypeerrordefinePropertyArray.prototype.flatMaplistenerseventDispatchernodejsUint8ArrayReactiveXreact-hooksclisyntaxerroriscensorflagxhrrecursivemoduletestestreecryptmulti-packageRegExp#flagsauthcloneowncachedom-testing-librarykoreanSystem.globallrueslintpluginl10nsetterinterruptshasOwndirectoryworkflowopensslhasOwnPropertycloudsearchspechardlinksclassnameFloat32Arrayerrorvarsbabel-corehelpersflatbabelInt32ArrayECMAScript 6sometransportpyyamljestread@@toStringTagiematchAlltrimStartchildconsumecall-boundvaluesyntaxvariablesconsolemkdirsmakeECMAScript 2019gitignorehttpharmonylinkbyteLengthbrowsersliststylesrulesgetspawnJSON-SchemaautoscalingfastclonetostringtagES2019promisehelperquerygradients css3reversedformreact-hook-formmatchcssminimaldependenciesefficientPromisestoragegatewayreactcommanderreal-timecommandkinesisreact poseforEachtypedarraysmapfile systemeslintgroupByes5positiveInt16Arraybinhas-ownerror-handlingnativestylesheetfastifyexecuteebstime0createdataViewlintrfc4122simpledbproxydynamodbenumerableWebSocketstraversecloudtrailmovewaitrangeerroremryamlAsyncIterator[[Prototype]]ObjectstreamclientlivefullwidthJSONdateutil.inspectdiffsequenceredactjson-schema-validationmkdirfunctioneveryinferenceECMAScriptObservablesharedmetadataStyleSheetpopmotionexeccalltranspileshimfunctionsbcryptasciiESnextendermatchescss nestingtc39mruimmerECMAScript 5routinglastexpressionpatchES7higher-orderparsingreplayspinnertypeES5assertsObject.assigndeepcopyFunction.prototype.nameesdropArray.prototype.filtereffect-tsworkerargvfixed-widthwaapisignalterminalwhichcolorses8removecoercibleprotocol-buffersinvariantidentifiersfunction.lengthsnsgrouppackage managerform-validationbindArray.prototype.containswindowssymlinkvalidaterequireserializegraphqlisConcatSpreadableoperating-systemfullfunctionalfilterqueueMicrotaskfastside6to5pushsameValueZerofindperformanceequaldragstyleguideRFC-6455arktypeiteratewhatwgschemebundlerregularweaksetpreprocessorjQuerymacosworkspace:*resolvesetImmediatea11yloggingexit-codeperformantfindLastnamesqstoobjectredux-toolkitRx__proto__containsenvironmentsless mixinsdotenvsesprogresssymbolsdescriptorsES8stylextermoptionnegative zeroReflect.getPrototypeOfexitargsendpointcheckRegExp.prototype.flagsjsonschemaglobalscryptonpmignorecodesstructuredCloneclass-validatorrgbstreamsaccessibilityCSSconcatMapkeyECMAScript 2022toolkitECMAScript 2017_.extendflatMapautoprefixerregexpspringFloat64Arrayregular-expressionArray.prototype.flattenTypedArrayobjectmobilezeroTypeScriptwalkArrayBuffer.prototype.sliceajvobjlibphonenumberSymbol.toStringTagfsless.jsi18nenvironmentprocessutilitiestypeoftelephonedomgetPrototypeOfwriteruntimedescriptorstringifierlinuxtranspilerStreamnegativeuuiddatastructurecjkwafimportfluxchannelincludesjsES2017trimEndes-shim APIconfigurablearraybufferlessbeanstalkbinarymomentdeepclonetermimmutablees2017deep-clonesettingsESvaluesURLSearchParamsES2018elasticacheString.prototype.matchAllnamesasyncObject.valuessliceinstallawsfps
4.9.83

10 months ago

4.9.82

10 months ago

4.9.81

10 months ago

4.8.81

10 months ago

4.8.80

10 months ago

3.8.80

10 months ago

3.7.80

10 months ago

3.6.80

11 months ago

3.6.79

11 months ago

3.6.78

11 months ago

3.6.77

11 months ago

3.6.76

11 months ago

3.5.76

11 months ago

3.5.75

11 months ago

3.5.74

11 months ago

3.5.73

11 months ago

3.5.72

11 months ago

3.5.71

11 months ago

3.5.70

11 months ago

2.5.70

11 months ago

2.5.69

11 months ago

2.5.68

11 months ago

2.5.67

11 months ago

2.5.66

11 months ago

2.5.65

11 months ago

2.5.64

11 months ago

2.5.63

11 months ago

2.5.62

11 months ago

2.5.61

11 months ago

2.5.60

11 months ago

2.4.60

11 months ago

2.4.59

11 months ago

2.4.58

11 months ago

2.4.57

11 months ago

2.4.56

11 months ago

2.4.55

11 months ago

2.4.54

11 months ago

2.4.53

12 months ago

2.4.52

12 months ago

2.4.51

12 months ago

2.4.50

12 months ago

2.4.49

12 months ago

2.4.48

12 months ago

2.3.48

12 months ago

2.3.47

12 months ago

2.3.46

12 months ago

2.3.45

12 months ago

2.3.44

12 months ago

2.3.43

12 months ago

2.3.42

12 months ago

2.3.41

12 months ago

2.3.40

12 months ago

2.3.39

12 months ago

2.2.39

12 months ago

2.2.38

12 months ago

2.2.37

12 months ago

2.2.36

12 months ago

2.2.35

1 year ago

2.2.34

1 year ago

2.2.33

1 year ago

2.2.32

1 year ago

2.2.31

1 year ago

2.2.30

1 year ago

2.2.29

1 year ago

2.2.28

1 year ago

2.2.27

1 year ago

2.2.26

1 year ago

2.2.25

1 year ago

2.2.24

1 year ago

2.2.23

1 year ago

2.1.23

1 year ago

2.1.22

1 year ago

2.1.21

1 year ago

2.1.20

1 year ago

2.1.19

1 year ago

2.1.18

1 year ago

2.1.17

1 year ago

2.1.16

1 year ago

2.1.15

1 year ago

2.1.14

1 year ago

2.1.13

1 year ago

2.1.12

1 year ago

2.1.11

1 year ago

2.1.10

1 year ago

2.1.9

1 year ago

2.1.8

1 year ago

2.1.7

1 year ago

2.1.6

1 year ago

1.1.6

1 year ago

1.1.5

1 year ago

1.0.5

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago