import{_ as i,o as t,c as a,ae as e}from"./chunks/framework.C8AWLET_.js";const g=JSON.parse('{"title":"♻️ Reactive Lists: $.for( )","description":"","frontmatter":{},"headers":[],"relativePath":"api/for.md","filePath":"api/for.md"}'),n={name:"api/for.md"};function l(h,s,r,p,k,d){return t(),a("div",null,[...s[0]||(s[0]=[e(`

♻️ Reactive Lists: $.for( )

The $.for function is a high-performance list renderer. It maps an array (or a Signal containing an array) to DOM nodes. Unlike a simple .map(), $.for is keyed, meaning it only updates, moves, or deletes the specific items that changed.

🛠️ Function Signature

typescript
$.for(
  source: Signal<any[]> | Function | any[], 
  render: (item: any, index: number) => HTMLElement, 
  keyFn: (item: any, index: number) => string | number
): HTMLElement
ParameterTypeRequiredDescription
sourceSignalYesThe reactive array to iterate over.
renderFunctionYesA function that returns a component or Node for each item.
keyFnFunctionYesA function to extract a unique ID for each item (crucial for performance).

Returns: A div element with display: contents containing the live list.


📖 Usage Patterns

1. Basic Keyed List

Always use a unique property (like an id) as a key to ensure SigPro doesn't recreate nodes unnecessarily.

javascript
const users = $([
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" }
]);

Ul({ class: "list" }, [
  $.for(users, 
    (user) => Li({ class: "p-2" }, user.name),
    (user) => user.id
  )
]);

2. Handling Primitive Arrays

If your array contains simple strings or numbers, you can use the value itself or the index as a key (though the index is less efficient for reordering).

javascript
const tags = $(["Tech", "JS", "Web"]);

Div({ class: "flex gap-1" }, [
  $.for(tags, (tag) => Badge(tag), (tag) => tag)
]);

🏗️ How it Works (The Reconciliation)

When the source signal changes, $.for performs the following steps:

  1. Key Diffing: It compares the new keys with the previous ones stored in an internal Map.
  2. Node Reuse: If a key already exists, the DOM node is reused and moved to its new position. No new elements are created.
  3. Cleanup: If a key disappears from the list, SigPro calls .destroy() on that specific item's instance. This stops all its internal watchers and removes its DOM nodes.

💡 Performance Tips


🧪 Summary Comparison

FeatureStandard Array.mapSigPro $.for
Re-renderRe-renders everythingOnly updates changes
DOM NodesRe-created every timeReused via Keys
MemoryPotential leaksAutomatic Cleanup
StateLost on re-renderPreserved per item
`,24)])])}const E=i(n,[["render",l]]);export{g as __pageData,E as default};