Reactively iterates over the items of an observable array or object, optionally rendering content for each item.
Automatically updates when items are added, removed, or modified.
Param: target
The observable array or object to iterate over. Values that are undefined are skipped.
Param: render
A function called for each item in the array. It receives the item's (observable) value and its index/key. Any DOM elements created within this function will be associated with the item, placed at the right spot in the DOM, and cleaned up when redrawing/removing the item.
Param: makeKey
An optional function to generate a sort key for each item. This controls the order in which items are rendered in the DOM. If omitted, items are rendered in array index order. The returned key can be a number, string, or an array of numbers/strings for composite sorting. Use invertString on string keys for descending order. Returning null or undefined from makeKey will prevent the item from being rendered.
// Add a new item - the list updates automatically setTimeout(() =>items.push('durian'), 2000); // Same for updates and deletes setTimeout(() =>items[1] = 'berry', 4000); setTimeout(() =>deleteitems[2], 6000);
// Sort by name alphabetically onEach(users, (user) => { $(`p:${user.name} (id=${user.id})`); }, (user) => [user.group, user.name]); // Sort by group, and within each group sort by name
Reactively iterates over the items of an observable array or object, optionally rendering content for each item.
Automatically updates when items are added, removed, or modified.
Param: target
The observable array or object to iterate over. Values that are
undefined
are skipped.Param: render
A function called for each item in the array. It receives the item's (observable) value and its index/key. Any DOM elements created within this function will be associated with the item, placed at the right spot in the DOM, and cleaned up when redrawing/removing the item.
Param: makeKey
An optional function to generate a sort key for each item. This controls the order in which items are rendered in the DOM. If omitted, items are rendered in array index order. The returned key can be a number, string, or an array of numbers/strings for composite sorting. Use invertString on string keys for descending order. Returning
null
orundefined
frommakeKey
will prevent the item from being rendered.Example: Iterating an array
Example: Iterating an array with custom ordering
Example: Iterating an object
See
invertString To easily create keys for reverse sorting.