@enzoaicardi/reactivity
v1.0.0
Published
A small modular interface for using signals in javascript
Downloads
75
Maintainers
Readme
Reactivity.js
A small modular interface for using signals in javascript
What is a signal ?
Largely inspired by the tc39 specification proposal
A signal is an object that represents a state, and has methods for retrieving the current state (reading the value) and methods for changing the state (writing the value).
When a signal's state is read, it retrieves the parent context and adds it to its dependencies. It can then update all its dependencies when its state changes.
Signals are often the most stable and easiest way to dynamically update data at no cost.
If this description sounds complicated, in practice using a signal is very simple. Here is a demonstration:
// setup a signal (named counter) and a reactive function (named counterLog)
const counter = new Signal(0);
const counterLog = new Reactive(() => console.log(counter.get()));
// activate counterLog
counterLog.use(); // this will trigger counterLog and print "0" in the console
// or...
counterLog.add(counter); // this will manually add counterLog to counter dependencies
counter.set(1); // this will trigger counterLog and print "1" in the console
counter.set(counter.value + 2); // this will trigger counterLog and print "3" in the console
counterLog.use(); // this will trigger counterLog and print "3" in the console
List of all exports
import {
Signal, // used to create a signal
Reactive, // used to create a reactive function
} from "@enzoaicardi/reactivity"; // cdn at https://cdn.jsdelivr.net/npm/@enzoaicardi/reactivity@latest/esm/reactivity.js
Intallations
NPM package
npm install @enzoaicardi/reactivity
import { Signal, Reactive } from "@enzoaicardi/reactivity"; // es modules
const { Signal, Reactive } = require("@enzoaicardi/reactivity"); // commonjs modules
CDN import
// es modules
import {
Signal,
Reactive,
} from "https://cdn.jsdelivr.net/npm/@enzoaicardi/reactivity@latest/esm/reactivity.js";
<!-- iife function execution -->
<script src="https://cdn.jsdelivr.net/npm/@enzoaicardi/reactivity@latest/iife/reactivity.js"></script>
<script>
// global object destructuration
const { Signal, Reactive } = Reactivity;
</script>