Minimal Bi-directional Object References

0.4.0 · active · verified Sun Apr 19

object-refs is a minimalist JavaScript library designed to establish and manage bi-directional references between objects. It's particularly useful in scenarios where maintaining explicit links between related objects, where one object's reference to another implies a reciprocal reference, is critical for data integrity or graph-like structures. The current stable version is 0.4.0. Given its `0.x.x` versioning, it likely follows an agile release cadence, introducing features and potentially breaking changes in minor versions. Its key differentiator is its focus on being minimal and providing robust type definitions for TypeScript users since `v0.4.0`, enabling safer refactoring and development compared to manual reference management.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to create a `Refs` instance, define reference properties, and establish/remove bi-directional links between two objects.

import { Refs } from 'object-refs';

// Define the properties that will hold the bi-directional references
const LEFT_REF = 'left';
const RIGHT_REF = 'right';

// Create a new reference collection for 'connection' type references
const connectionRefs = new Refs({ 
  name: 'connection',
  collection: 'connections',
  target: LEFT_REF,
  source: RIGHT_REF
});

// Example objects
const nodeA = { id: 'nodeA', connections: [] };
const nodeB = { id: 'nodeB', connections: [] };

// Add a bi-directional reference between nodeA and nodeB
// This will add nodeA to nodeB.connections and nodeB to nodeA.connections (via the ref properties)
connectionRefs.bind(nodeA, nodeB);

console.log('Node A connections:', nodeA.connections.map(c => c.id));
// Expected: Node A connections: [ 'nodeB' ]

console.log('Node B connections:', nodeB.connections.map(c => c.id));
// Expected: Node B connections: [ 'nodeA' ]

// Clean up references
connectionRefs.unbind(nodeA, nodeB);

console.log('Node A connections after unbind:', nodeA.connections.map(c => c.id));
// Expected: Node A connections after unbind: []

view raw JSON →