1.3.17 • Published 1 year ago

@juigorg/quidem-unde-corporis v1.3.17

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year 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 @juigorg/quidem-unde-corporis
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
iebreakes-abstractenumerablecopycodesargumentpatchlinewrapdeep-copysettingsbyteOffsetponyfilltslibdeletereduxHyBitaskvalidstringifierec2utilityrobusttoStringTages6WebSocketsrfc4122ecmascript_.extendtoobjectgetdirectoryratelimitRFC-6455whatwgcall-boundcjkargvidentifiersxhrlogeslintpluginInt32Arrayglaciergesturescall-bindcolourstructuredClonerateclienttoArrayarktypenegative zeroStreamshttpdebugtrimStartoncehelpersEScloudwatchinvariantflatMapkinesisrdselasticachejestzodstableinputquerygetintrinsicobjectReactiveExtensionsnodeArray.prototype.findLastformatpushobjmonorepokeyrgbfast-copyjson cachecharactersapireal-timezerokarmaeventskoreanes-shim APIreadablestyle0quoteECMAScript 6variablesconsumevarsparserESnexttaploggerawsmapreduceyuptrimRightUint8ArrayswfreduceasciistatelessMicrosoftentriesassertiontakepersistentprotobufspinnerstyled-componentsSymbolfiltertypesReactiveXredactsetterspringfastifycmdparentjsexpressionstylingjavascriptwafeslintconfigECMAScript 2019concurrencysesTypeScriptdom-testing-libraryFunction.prototype.nameschemasimpledbqueueMicrotaskamazonhas-owniterationjsdomfast-cloneenvfull-widthdataviewcommanderES2016WebSocketcallboundttyes7apollotostringtaghooksrandomroutingRxduplextapeimmutableSymbol.toStringTagequalityelbMapautoprefixerconfigimmerutilinstallerformattinghigher-ordergraphqlparsingArray.prototype.containslocationcharsetcomputed-typesreactcreateeslint-pluginES8waitlookqseventDispatchersortednopeArray.prototype.findLastIndexfastcopymkdirserializerString.prototype.matchAllrm -rfECMAScript 7key valuees2017wgetbatchenvironmentstestresolveroute53assignmatchesreademrconvertexecpromisesES2019inferencesetPrototypeOfwalkflagsbufferinECMAScript 3fpsObject.valuescolumnistanbulYAMLscheme-validationchannelisUint16Arrayi18nsetImmediatepackageforEachdefinearttypescriptdescriptionmakecommandruntimewarningopenhardlinksrmdirextensiongetPrototypeOfajaxjshintObject.istoolsconfigurabletypesafeprogressFloat32Arrayes-shimsnpmform-validationcloudtrailtypedarrayrangeerrorStyleSheetenderreducerbyteLengthdommrucloudsearchstarterUnderscoreexe@@toStringTagtelephonegroupsuperagentdirstoragegatewaycssprivate datakeysfast-deep-copyes5pnpm9requesttrimLeftfindLastsymbolarraybufferpolyfillwordbreakchaiairbnbcallbindsyntaxnativephonestreamwhichtimeArrayBuffer.prototype.slicefromloadbalancingbundlingenvironmentregexpidleglobaltyped arraygdprRxJSpropposexdgfindLastIndexmime-dbextendsequencekey parnamecryptocharacterthrottleCSSStyleDeclarationURLtoSortedsymlinksshameveryerrordropschemefunctionalwordwrapeast-asian-widthmoveoptimizerbannersymbolsStreamchinesehelperfinddraggetOwnPropertyDescriptoriamjsxgroupByjoishimstylesassertArray.prototype.filterlintcoreformperformantIteratorvisuala11yexecutableRegExp.prototype.flagsanimationECMAScript 2017$.extendcoercible3dansipipefastcloneurldataViewbytepostcss-plugintesterisConcatSpreadableopenspruneincludesdefinePropertynameshashgetoptArraycore-jsconcatMapbuffersshrinkwraplengthsomechecknumberinspectcoverageiteratortypeminimalbundlerframerECMAScript 2015__proto__valuees2018eslints3AsyncIteratorwaapiconcatInt8ArrayInt16ArrayserializationmimeplugincompileravapyyamlomitES2018Array.prototype.includessimple cachearraysbddoffsetfunctionswritepropertypromisecallbacksortworkerchildterminaldiffworkspace:*symlinkcolorserializetypeerrortypeofprotoargumentsObject.getPrototypeOftrimEndsearchurlsequalTypedArrayFloat64ArrayES3WeakMapcallhasBigUint64ArraysuperstructsetdateslotcloudformationfigletagentconsoleprefixES5openerArray.prototype.flattencollection.es6sameValueZero256columnslockfilelastreact-testing-libraryTypeBoxObservableES6Uint8ClampedArraytypedarraysclass-validatorspecpackage managerES2017Uint32ArraylinkiterateObject.assignpackage.jsonassertsbluebirddescriptorsdotenvreact poseinternalmimetypeseditorstringifylimiteddeepcollectioninternal slotRegExp#flagsinstrumentationtextoptimistspawnnodejscensorglobalsuuidsyntaxerrorpreserve-symlinksdatastructurecontainsowncommand-lineautoscalingtrimreact-hookslook-upfetchpositivedayjs-0streams2lrureadablestreames2015metadataendpointuninstalltypanionlimitparentsrapidjsonpathescapeloadingglobebstsviewArrayBuffer#slicecircularmomentjapaneseutil.inspectworkflowweakmapchromiumlazySetsharedarraybufferunicodecurldescriptorECMAScript 5modulees8eventEmitterString.prototype.triml10nprivatecolorsguidmergefile cachespeedES2022removeoptiontermweaksetbindasyncloggingdeepcopyproxylistenersimportexportmobilePushargsastboundfast-deep-cloneECMAScript 2018mkdirsjQueryfixed-widthstdlibdeterministicthreebrowserslistcode pointsdeep-clonedynamodbES2021estreejsonhttpsECMAScript 2023awesomesauceArray.prototype.flatmake dirReflect.getPrototypeOfES7PromiseObservablesgetterjsdiffBigInt64ArrayObject.fromEntriesidregular expressiontraversereact animationindicatorfile systemaccessorfullwidthfolderparse[[Prototype]]clistartpathprocessredirecticonvcomparepackagesefficientpropertiesreuseinstallelectronlaunchpicomatchdeepclonejasmineArrayBuffertouchregularsaferegular expressionsstyleguideflattenfind-upsideES2023busypostcssfscloudfrontwebsitexdg-openquerystringformsutilitiestypedECMAScript 2021espreewalkingObjectcss-in-jsvalidationio-tsemitfindupfileObject.definePropertyECMAScript 2022ES2020shellURLSearchParamsaccessibilityfullappObject.keysvpcnegativeesJSONoutputbeanstalkexpressCSShasOwnvaluessnsdependency managerECMAScript 2016spinnersflaghookformupprototypestringwritabletddextrarm -frajvchromebrowserlistrmimportlibphonenumberregexArray.prototype.flatMapmatchAllicushebangprotocol-buffersqueue
1.3.17

1 year ago

1.2.16

1 year ago

1.2.17

1 year ago

1.2.14

1 year ago

1.1.14

1 year ago

1.2.15

1 year ago

1.1.13

1 year ago

1.1.12

1 year ago

1.1.9

1 year ago

1.1.8

1 year ago

1.1.11

1 year ago

1.1.10

1 year ago

1.1.7

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