1.2.11 • Published 5 days ago

@kollorg/fugiat-cum-libero v1.2.11

Weekly downloads
-
License
MIT
Repository
github
Last release
5 days ago

Delegate.ts

A simple event emitter with TypeScript inference

Code preview

const onDataProcessed = new Delegate<[data: Uint8Array]>();

// adding a module or global-scoped callback
const processData = function(data: Uint8Array) {
    // ... process data ...
};

onDataProcessed.addListener(processData);

// notify listeners with data
onDataProcessed(new Uint8Array(...));

Add a member function callback

class DataReceiver {
    constructor() { }

    handleData(data: Uint8Array) {
        // ... process data ...
    }
}
const dataReceiver = new DataReceiver();

// specify `this` context as the second argument
onDataProcessed.addListener(dataReceiver.handleData, dataReceiver);

Remove listeners

// module/global-scoped function
onDataProcessed.removeListener(processData);

// member function
onDataProcessed.removeListener(dataReceiver.handleData, dataReceiver);

"Once" pattern

const fireAndForget = function(data: Uint8Array) {
    // do something

    onDataProcessed.removeListener(fireAndForget);
}

onDataProcessed.addListener()

Asynchronous call

// await each async callback sequentially
await onDataProcessed.asyncSeq(new Uint8Array(...));

// allow each async callback to resolve freely
await onDataProcessed.asyncAll(new Uint8Array(...));

Delegate group

// object literal pattern is recommended for type inference
const trackEvents = {
    onMarker: new Delegate<[name: string, timestamp: number]>(),
    onTrackEnd: new Delegate(),
    onTransition: new Delegate<[from: number, to: number]>()
};

// in a class
class TrackManager {
    constructor() { }

    events = {
        onMarker: new Delegate<[name: string, timestamp: number]>(),
        onTrackEnd: new Delegate(),
        onTransition: new Delegate<[from: number, to: number]>()
    }
}

Please read the Delegate.ts and Delegate.test.ts files for further information on usage.

Installation

npm install @kollorg/fugiat-cum-libero
Non-npm methods
  1. TypeScript Project
  • Download & drop Delegate.ts into a TypeScript project
  1. JavaScript Project
  • Clone the repo, run either tsc in the root directory, or bun i && bun run build
  • Drop the built dist/Delegate.js into your project.

Compatibility

  • Works in node, bun, browser, etc.
  • Requires an ES6+ environment, due to the use of Proxy and Promise

Development

Bun is used for testing

To install dev dependencies:

bun install

To run tests:

bun test

To build:

bun run build
getoptec2es2016rfc4122mkdirponceratelimitCSSStyleDeclarationswfmergeRxJSroutingquerycss-in-jswordwraphasOwnqselasticachelazyregulardefinePropertybrowserlistvalidateArray.prototype.flattenloadbalancingansiES2017ES2020folderspinnersjsdiffcolorRegExp#flagspersistentnamefile cacheconcurrencydefaultidlejQueryreuseMaplinewrapobjecttexttslibgroupByschememake dirpushshelljsxextendES2015immersetPrototypeOfroute53widthoutputObject.keyscolorsjoistarterresolvechineseformaticonvmaketypedconfigiterationarrayscachefinduphelperscommandergetOwnPropertyDescriptorBigInt64ArraytypedarrayssidesharedarraybufferArray.prototype.findLasthooksWebSocketkinesisopenerRegExp.prototype.flagspackagesdescriptorsawswritetaskutilitywalkastclientwhatwglanguagekoreangesturesconcatMaprmdirdayjsurltoobjectECMAScript 5toStringTagyamlObject.assignsliceproxywaapibreakspinnertyped arrayimmutabletrimLeftconvertreact-hook-formtouchspeedlastmulti-packageECMAScript 7offset.envsuperagentES2023Float32Arraystringifiercolumnsagentxdgemojipropvestrm -rfgroupjshintprocessdeterministicpropertyreducedatearraynpmanimationdefineconsolevariablesES2022consumedropavabeanstalkmkdirschannelregular expressionsreal-timeformscloudformationcheckmatchesSetthreeinputendpointzod0prunesuperstructparserdescriptionimportlimitcloudsearchpluginnumberdragES8wgetutil.inspectpathObjectpolyfillxdg-openObject.valuesArray.prototype.flatMaploadingmime-dbpackagepositivestatelessquerystringesreact-hooksrequireWeakSetes7terminalcircularbrowserdynamodbeslintxhroptimistwalkingUnderscoresyntaxerrorenvironmentsMicrosoftprotocol-buffersquotees2015safees8formattingflatMapfull[[Prototype]]rmerrorperformanceairbnbPushfilenegative zerotrimRightfullwidthapiArrayBufferthroatdomECMAScript 2015hasOwnPropertyArray.prototype.containstrimEndgraphqlhashidentifiersECMAScript 2023importexportprogressthrottlesnspnpm9stylesprotobufform-validationcollectionwritableeslint-pluginomitHyBiES7sharedequalitytsparentsortwarningviewtypaniones6ECMAScript 2019eslintconfigcmdtypeerrorparsepopmotionstylematchregexpsymlinkeventDispatcheraccessibilitylruexpressioncolouri18njavascriptkeysUint32ArraylintvalidationinstallerfunctionECMAScript 2017descriptorcollection.es6inAsyncIteratorsimpledbes5utilitiesstyleguideflagminimalfindLastcompilerredirectRFC-6455promisesObject.fromEntriesiddataqueuebusyintrinsicjapanesepyyamlnodeprefixfiltertesterassertiontoSortedtrimStartcoreprettymomentrobustweaksetenumerablecallbacklibphonenumberreadablestreamrandomdependency managergetPrototypeOftypeartstreamappflatflagslimitedstructuredCloneoptionshebangArrayBuffer#sliceguidincludespackage managerbufferString.prototype.trimdeepcopycjkeventsworkerECMAScript 6codesweakmaphelperemitargscoercibleio-tsextensionprotogetes-abstractgetterbrowserslistexpressdebuggerjsonbluebirdSymbol.toStringTagstdlibnamesiames2018serializercallbinditeratorlengthcode pointsserializenodejsES2019moduleinternal slotasyncsetterbyteLengthreactsameValueZerordsfastifyhas-ownttytoolkiteditorindicatorurlsdeep-copytapelaunchlocationSymbolURLSearchParamsexevaluecore-jsscheme-validationcoveragesortedJSON-Schemauuidtypesunicodewafregular expressionruntimeflattendirectoryprivate dataparsingtimeworkflowkarma256awaitUint8ClampedArraysqstc39internalvisualfile systemschemaStreamarktypereducerrecursivetostringtagloggerWeakMapuninstalles2017Observablesyntaxstreams2validprototypebindrateslotredactwordbreaktapicucontainsdataviewponyfillbatchcommand-lineES2016cryptoparentsgetintrinsiclistenerszeroinstrumentationjson cacheString.prototype.matchAllboundRxpromisecompareexecutableconcatstylingprivateReactiveExtensionsJSONinspecthttpsfpsdom-testing-libraryESdiffsymlinkscolumnmetadataeveryautoprefixermobileTypedArrayargvstreamsinstallcharacterschild__proto__assignjsvpctraversechaiArray.prototype.includesfastCSStestrangeerrorworkspace:*WebSocketsTypeScripteslintpluginfastclonereadopensupfindLastIndexenvironmentglobalelbES2021pipecurlkey valuematchAllcreateshamobjmovejsonpathlookES3@@toStringTagglaciers3xtermdependenciesReflect.getPrototypeOfposecopykey parsymbolInt16Arrayaccessorpreserve-symlinksamazoninferencefull-widthendercallapollofunction.lengthhigher-orderargumentsescapewhichcloudwatchajvargumentrapidphoneiehardlinksemrsettingsfastcopystartECMAScript 3utilfindl10n-0hasbddrm -frfunctionalownfixed-widthtoolsdataViewshrinkwrapcall-bindexecopenmonoreporeduxpostcss-plugintoArrayArray.prototype.findLastIndexautoscalingbannerYAMLcssObject.getPrototypeOfspringbundlingduplexglobalsfigletstoragegatewayvarsajaxconfigurablees-shim APIbyteOffsetreact animationspawnpicomatchbytecharactertrimbuffersrouteUint8Arrayequalproperties
1.2.11

5 days ago

1.2.8

8 days ago

1.2.7

9 days ago

1.2.9

7 days ago

1.2.10

6 days ago

1.2.6

10 days ago

1.1.6

11 days ago

1.1.5

12 days ago

1.1.4

13 days ago

1.0.4

14 days ago

1.0.3

15 days ago

1.0.2

16 days ago

1.0.1

17 days ago

1.0.0

18 days ago