Skip to content

Latest commit

 

History

History
256 lines (198 loc) · 7.38 KB

readme.md

File metadata and controls

256 lines (198 loc) · 7.38 KB

spect spect    npm bundle size npm

Observe selectors in DOM.

spect( container=document, selector, handler? )

Observes selector in container, invokes handler any time matching elements appear.
Handler can return a teardown function, called for unmatched elements.
Returns live collection of elements.

import spect from 'spect';

// assign aspect
const foos = spect('.foo', el => {
  console.log('connected');
  return () => console.log('disconnected');
});

// modify DOM
const foo = document.createElement('div');
foo.className = 'foo';
document.body.append(foo);
// ... "connected"

foo.remove();
// ... "disconnected"

spect(element[s], handler)

Listens for connected/disconnected events for the list of elements. (alternative to fast-on-load)

const nodes = [...document.querySelectorAll('.foo'), document.createElement('div')];

// assign listener
spect(nodes, el => {
  console.log("connected");
  return () => console.log("disconnected");
});

document.body.appendChild(nodes.at(-1))
// ... "connected"

nodes.at(-1).remove()
// ... "disconnected"

Live Collection

Spect creates live collection of elements matching the selector. Collection extends Array and implements Set / HTMLColection interfaces.

const foos = spect(`.foo`);

// live collection
foos[idx], foos.at(idx)                       // Array
foos.has(el), foos.add(el), foos.delete(el)   // Set
foos.item(idx), foos.namedItem(elementId)     // HTMLCollection
foos.dispose()                                // destroy selector observer / unsubscribe

Technique

It combines selector parts indexing from selector-observer for simple queries and animation events from insertionQuery for complex selectors.

Simple selector is id/name/class/tag followed by classes or attrs.

  • #a, .x.y, [name="e"].x, *, a-b-c:x - simple selectors.
  • a b, #b .c - complex selectors.

Alternatives

element-behaviors, insertionQuery, selector-observer, qso, qsa-observer, element-observer, livequery, selector-listener, mutation-summary, fast-on-load, selector-set, rkusa/selector-observer. css-chain