Plug-and-play, faster-than-native promise/callback event emitter

Overview


kNow

Blazing-fast callback/promise-based events with a tiny footprint

What is this?

With kNow (pronounced "now"—the k's silent), JavaScript event management has never been more intuitive—or lighter-weight. Want to append custom actions to functions on-the-fly? To use awaitable timers to pause and resume execution at any time? To create large numbers of listeners without worrying about performance degradation? If so, you want kNow.

Via https://jsben.ch/ZESbj (Avg. over 25 runs)

Originally developed for use in Membrane, kNow is a fully functional, if lightweight, native event-management utility for any use-case.

Getting Started

Node.js + npm

Installation:

To install in the root of your node project:

npm i @elijah-bodden/know

Or else globally:

npm i @elijah-bodden/know -g

Use in-script

To import the module into your node script, simply paste the following line at the very top:

const kNow = require('@elijah-bodden/know')

Then, to create a usable intance, add const someVariable = new kNow() anywhere, where 'someVariable' is the name you wish to access it by.

HTML script tag

Inclusion

To include the script in your HTML, add the following tag to the top of your document:

<script src="https://cdn.jsdelivr.net/npm/@elijah-bodden/know/index.min.js">

Use in-script

Just as with node, simply drop in const someVariable = new kNow() anywhere in your script, changing 'someVariable' to the name you want to reference the instance with.

Examples

Pause function execution for n milliseconds

  const kNow = require("@elijah-bodden/know");
  const know = new kNow()
  
  async function test() {
    console.log("foo")
    console.log("bar")
    //Creates and awaits a promise that resolves in 3000ms or 3 seconds
    await know.in(3000)
    console.log("baz")
  }
  
  test()
  
  /* Expected Output:
    1. "foo"
    2. "bar"
    *Three-second pause*
    3. "baz"
  */

Track changes to a variable

  const kNow = require("@elijah-bodden/know");
  const know = new kNow()
  
  var variable
  
  function setVariable(newVal) {
    variable = newVal
    know.dispatch("variableChanged", variable)
  }
  
  setInterval(() => setVariable(Math.random()), 1000)
  
  //Listener callbacks can be created and destroyed at any time, on-the-fly.
  const changeListener = know.when("variableChanged", (newVal) => console.log(`Variable "variable" was changed to ${newVal}.`))

  setTimeout(() => know.clearWhen(changeListener), 5000)
  /* Expected Output:
    *1 second pause* "Variable was changed to (some value)" x 4
  */

Call function X next time Y completes

  const kNow = require("@elijah-bodden/know");
  const know = new kNow()

  function unpredictableFunction() {
    for (let i = 0; i < 10000000; i++) {
      //Doing some valuable operations
    }
    console.log("Alerting that task was completed.")
    know.dispatch("taskCompleted")
    setTimeout(unpredictableFunction, Math.floor(Math.random()*10000))
  }
  
  setTimeout(unpredictableFunction, Math.floor(Math.random()*10000))
  
  know.next("taskCompleted").then(() => console.log("Task completed!"))
  
  /* Expected Output:
    *Indefinite pause*
    1. "Alerting that task was completed."
    2. "Task completed!"
  */

Methods

Use any of the following functions on a kNow instance to implement powerful, high-speed event handling in a snap.

Command Description
constructor(number) When you initialize kNow, you can optionally pass a single argument, the length of time, in milliseconds, after which each next listener automatically expires.
when(number | string, function) Automatically attatches a callback, its second argument, which will run every time the first argument's value is dispatched. The function returns an instanceID object which can be passed into clearWhen to destroy the listener.
clearWhen(object | string | number | undefined) Accepts either a string or a number, an instanceID object, or no value. If it recieves a string or a number, kNow will unregister all when callbacks bound to that dispatch value; if it instead gets an instanceID created by when, only the callback created by this call will be destroyed. Otherwise, if the value is undefined, all callbacks registered to all ID's will be destroyed simultaneously.
dispatch(number | string, any) Immediately resolves all promises bound through next to the first parameter, and invokes all callbacks attatched to it by when. All promises will resolve to the second argument, which will also be passed to all callback functions.
forceReject(number | string, any) forceReject does the exact opposite of dispatch, batch-rejecting all promises attatched to the first argument and setting the reasons to the second.
next(number | string, number | undefined) next returns a promise which may either be resolved by dispatching the value provided as the first parameter, or rejected through clearNext or forceReject. Optionally, a second argument, a timeout, may be specified, after which to automatically reject to promise. If this argument is omited, it will default to the value provided to the constructor, and if this too is undefined, there will be no timeout.
clearnext(...string | number | undefined) Accepts a list of dispatch ID's; if none are provided, it defaults to every registered ID. Each promise registered to each of these ID's is forceRejected with the reason "flushed".
in(number) Returns a promise which will resolve to undefined in the specified number of milliseconds.
clearIn() Immediately forceRejects every promise created by in

License

kNow is distributed under the MIT license. See the LICENSE file for more information.

Contributing

Any and all contributions are greatly appreciated. If you want to see this project grow as much as I do, there are several ways to help. Firstly, if you see something you think you can improve within the code, please fork the repository and make a pull request once you have made any changes you'd like to see. If you just have an idea, or spot a bug, that's great too! In this case, please file an issue with a corresponding bug or enhancement tag. Oh, and if you like what you see here, please feel free to leave a star on the project, it would mean a ton to me.

Contact

Elijah Bodden - [email protected]
Project - https://github.com/Elijah-Bodden/kNow
npm - https://www.npmjs.com/package/@elijah-bodden/know

You might also like...

A daily print-and-play roguelike adventure you can play offline.

A daily print-and-play roguelike adventure you can play offline.

Chronicles of Stampadia A print-and-play roguelike with a new adventure every day! Play today's adventure | Read the manual | Learn how to play | Disc

Oct 15, 2022

Danger is near (play to earn game, gamefi on near chain testnet) - user play as a fireknight in a PIXELVERSE world who go to forest and kill monster.

Danger is near (play to earn game, gamefi on near chain testnet) - user play as a fireknight in a PIXELVERSE world who go to forest and kill monster.

Danger is near (play to earn game, gamefi on near chain testnet) - user play as a fireknight in a PIXELVERSE world who go to forest and kill monster. User can earn $DANGER token and score to compete with others user.

Dec 30, 2022

io-ts Typed Event Bus for the runtime of your Node.js application. A core for any event-driven architecture based app.

Typed Event Bus Based on io-ts types, this bus provides a handy interface to publish and consume events in the current runtime of the Node.js process.

May 23, 2022

'event-driven' library aims to simplify building backends in an event driven style

'event-driven' library aims to simplify building backends in an event driven style

'event-driven' library aims to simplify building backends in an event driven style(event driven architecture). For message broker, light weight Redis Stream is used and for event store, the well known NoSQL database, MongoDB, is used.

Jan 4, 2023

An AWS Cloud Native application using CDK that defines a Serverless Event Driven application for interacting with Twitter and utilising Machine Learning / AI as a Service.

An AWS Cloud Native application using CDK that defines a Serverless Event Driven application for interacting with Twitter and utilising Machine Learning / AI as a Service.

AWS Serverless Event Driven Twitter Bot An AWS Cloud Native application using CDK (Written in TypeScript) that defines a Serverless Event Driven appli

Dec 18, 2022

Write and read comments on every page with a simple plug-in for your browser

Write and read comments on every page with a simple plug-in for your browser

Licom - comments on every webpage Licom is a simple plugin for your browser that adds the feature to leave comments on every page, even if it doesn't

Aug 4, 2022

A Hackable Markdown Note Application for Programmers. Version control, AI completion, mind map, documents encryption, code snippet running, integrated terminal, chart embedding, HTML applets, plug-in, and macro replacement.

A Hackable Markdown Note Application for Programmers. Version control, AI completion, mind map, documents encryption, code snippet running, integrated terminal, chart embedding, HTML applets, plug-in, and macro replacement.

Yank Note A hackable markdown note application for programmers Download | Try it Online Not ecommended English | 中文说明 [toc]{level: [2]} Highlights

Dec 31, 2022

Plug-in for Obsidian.md which will create Notes from JSON files

Import JSON This plug-in provides you with the tools to import your favourite JSON tables. A magnifying-glass icon will appear in the left margin when

Dec 31, 2022

A lightweight tooltip plug-in library

popper-next 是一款轻量的 Tooltip 插件 vue、react安装使用 推荐yarn yarn add popper-next 或者 cnpm install popper-next -S 在html页面中如何使用 script src="https://unpkg.com/pop

Dec 7, 2022
Releases(v1.1.5)
Owner
Elijah Bodden
Elijah Bodden
A TypeScript friendly event emitter with easy re-emitting events

remitter A TypeScript friendly event emitter with easy re-emitting events. Install npm add remitter Usage import { Remitter } from "remitter"; interf

CRIMX 5 Dec 28, 2022
👀 A Node.js event emitter works in the browser

observer-emit ?? A Node.js event emitter works in the browser. Install using npm $ npm i observer-emit using yarn $ yarn add observer-emit using pnpm

Akashi 3 Jul 2, 2022
Add class(es) to DOM elements while waiting for async action. Promise or callback.

jquery.loading Add class(es) to DOM elements while waiting for async action. Promise or callback. Install The simplest way is to include loading.js in

Dumitru Uzun 1 Mar 26, 2022
JavaScript micro-library: pass in an element and a callback and this will trigger when you click anywhere other than the element

Add a click listener to fire a callback for everywhere on the window except your chosen element. Installation run npm install @lukeboyle/when-clicked-

Boyleing Point 5 May 13, 2021
Robust, plug & play generator for Bootstrap toasts.

Bootstrap Toaster Robust, plug & play generator for Bootstrap toasts. Supports Bootstrap 4 and Bootstrap 5. Demo A demo page is available at bootstrap

Peyton Gasink 22 Dec 21, 2022
Inside-out promise; lets you call resolve and reject from outside the Promise constructor function.

Inside-out promise; lets you call resolve and reject from outside the Promise constructor function.

Lily Scott 3 Feb 28, 2022
Adds promise support (rejects(), doesNotReject()) to tape by decorating it using tape-promise.

Tape With Promises Adds promise support (rejects(), doesNotReject()) to tape by decorating it using tape-promise. Install npm install --save-dev @smal

Small Technology Foundation 3 Mar 21, 2022
2x times faster than chalk and use 5x less space in node_modules

Nano Colors A tiny and fast Node.js library for formatting terminal text with ANSI colors. It is 2 times faster than chalk. Both loading and calls. No

Andrey Sitnik 886 Dec 30, 2022
🎮 The only Front-End Performance Checklist that runs faster than the others

Front-End Performance Checklist ?? The only Front-End Performance Checklist that runs faster than the others. One simple rule: "Design and code with p

David Dias 15.5k Jan 1, 2023
An all new Titanfall VPK unpacker. Over 2x faster than the most popular alternative!

Harmony VPK Tool An electron-based app for unpacking Respawn VPK files. Super-fast and made with ♥ Why use Harmony VPK Tool over cra0's VPKTool? It's

Harmony 16 Dec 19, 2022