listen-proxy
TypeScript icon, indicating that this package has built-in type declarations

1.5.3 • Public • Published

Listen Proxy

Node.js CI version

license Coverage: 100%

dependancies downloads

stargazers number of forks


What?

This is a utility npm package that allows you to bind a set of callbacks "listeners" to an object, with the createProxy function. Those listeners will be fired when a property is added, deleter or modified.

The listener methods given have to have a specific name, mainly, given a property in or object named example, you will havee access to 3 methods:

  • onExampleAdd: Callback that will be fired when the example property is added.
  • onExampleDelete: Callback that will be fired when the example property is deleted.
  • onExampleChange: Callback that will be fired when the example property is changed.

Why?

This package was created because I wanted to test some TS features, credit must be given to Jack Herrington, since a video he did about mapped types was the inspiration for this package, I'll leave the video at the bottom of the readme.

How?

To use this package, you have to install it with npm or yarn, and then import it in your project.

npm install listen-proxy
yarn add listen-proxy
import { createProxy } from "listen-proxy";

Once you have imported the package, you can use the createProxy function to create a proxy object, and then bind your listeners to it.

const dog = {
  name: 'Rex',
  age: 3,
};

const dogListeners = {
  onNameChange: (value, oldValue, target) => {
    console.log(`The dog's name changed from ${oldValue} to ${value}`, target);
  },
  onAgeDelete: (oldValue) => {
    console.log(`The dog's age was deleted, his age was ${oldValue}`);
  },
  onBreedAdd: (value, target) => {
    console.log(`The dog's breed was added, his breed is ${value} his name is ${target.name}`);
  },
};

const proxyDog = createProxy(dog, dogListeners);


proxyDog.name = 'Rexy'; // The dog's name changed from Rex to Rexy { name: 'Rexy', age: 3 }
delete proxyDog.age; // The dog's age was deleted, his age was 3
proxyDog.breed = 'Labrador'; // The dog's breed was added, his breed is Labrador his name is Rexy

As you can see, the createProxy function takes two arguments, the first one is the object you want to bind the listeners to, and the second one is an object containing the listeners.

This project has full TypeScript support, you will find the following type:

import { Listeners } from "listen-proxy";

Which you can use to type your listeners object.

If you find any bugs or errors, please let me know by creating an issue here.

And if you want to contribute, please feel free to do so by opening a PR.


No Bs Ts video

Package Sidebar

Install

npm i listen-proxy

Weekly Downloads

0

Version

1.5.3

License

MIT

Unpacked Size

8.68 kB

Total Files

5

Last publish

Collaborators

  • xavifabregat