array-observer
TypeScript icon, indicating that this package has built-in type declarations

1.0.4 • Public • Published

Array Observer

Travis-ci CircleCI GitHub issues License: MIT Download version

Hello Folks! 😎🎶

This is just a simple array observer, which listen to array's addition, modification and removal of each element and triggers the provided callback with respective metadata. We can use any of the array modification methods on proxyArray instance.

How it works under the hood?

Proxy plays important role where it helps to get the hook of array modification overall and then we have a piece of logic where it detect what kind of operation user performed.

Why do we need to use this package?

Proxy won't provide information about what kind of operation user has been made on the array. So, I wrote a simple logic to fulfill this usecase.

🔥I also added types🔥. Typescript lovers smash the star ⭐️

Installation

npm i array-observer

Usage (ESM & CJS)

import { observer, ActionType } from 'array-observer';

const tasks = [
  {
    name: 'task1: learn JS'
  },
  {
    name: 'task2: do POC'
  }
];

const proxyTasks = observer(tasks, (metadata) => {
  console.log(
    // Index of which addition, modfication or removal has been done
    metadata.index,

    // Type of action added, modified or removed
    metadata.type === ActionType.Added,

    // Actual array
    metadata.target,

    // Item of which addition, modfication or removal has been done
    metadata.value
  );
});

proxyTasks.push({
  name: 'UI: create a polyfill for map'
});

proxyTasks.pop();

CDN usage (UMD)

<script src="https://cdn.jsdelivr.net/npm/array-observer@latest/dist/array-observer.umd.js"></script>
<script>
  const tasks = [
    {
      name: 'task1: learn JS'
    },
    {
      name: 'task2: do POC'
    }
  ];

  const proxyTasks = Array.observer(tasks, (metadata) => {
    console.log(
      // Index of which addition, modfication or removal has been done
      metadata.index,

      // Type of action added, modified or removed
      metadata.type === Array.ActionType.Added,

      // Actual array
      metadata.target,

      // Item of which addition, modfication or removal has been done
      metadata.value
    );
  });

  proxyTasks.push({
    name: 'UI: create a polyfill for map'
  });

  proxyTasks.pop();
</script>

Support through below platforms:

patreon

Buy me a coffee

Dependencies (0)

    Dev Dependencies (8)

    Package Sidebar

    Install

    npm i array-observer

    Weekly Downloads

    3

    Version

    1.0.4

    License

    MIT

    Unpacked Size

    24.9 kB

    Total Files

    25

    Last publish

    Collaborators

    • haribalajiravi