qob
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

qob (Query'd Observer)

Listen for DOM changes to elements that match a given query selector.

npm version

API

API docs for v1.0

Functions

qob()

qob(
    querySelector: string, 
    callback: (matched: ObservedMutationDictionary) => void
): MutationObserver

Start listening for changes to the document and use the callback to list any changes to elements matching the query selector.

  • querySelector: used to match MutationRecords created from DOM changes.
  • callback: called when the inner MutationObserver observes some event. Takes one ObservedMutationDictionary as a parameter.

qob.for()

qob.for(target: Node): (
    qs: string,
    cb: (rec: ObservedMutationDictionary) => void
) => MutationObserver

Create a new qob function with a non-default (document) scope.

  • target: the new qob function will scope to this element instead of the default document.

Structures

ObservedMutationDictionary {
    childList: MutationRecord[]
    attributes: MutationRecord[]
    characterData: MutationRecord[]
    all(): MutationRecord[]
    nodes(): Node[] 
}
  • childList: All matched MutationRecords with type "childList".
  • attributes: All matched MutationRecords with type "attributes".
  • characterData: All matched MutationRecords with type "characterData".
  • all(): All matched MutationRecords.
  • nodes(): All nodes from target, removedNodes, and addedNodes found in matched MutationRecords.

Example

import qob from 'qob'

// Start observing document for changes related to div#my-id
qob('div#my-id', (records) => {
    // All matching events with type 'childList'
    records.childList.forEach(mutationRecord => {
        // ...react to the mutations...
    })

    // All matching events with any type.
    const list = records.all()
        .map(mutationRecord => mutationRecord.target)

    // All affected nodes from anywhere in the matched records.
    const nodeArray = records.nodes()
})

// Creates a new qob function (like the one called above). 
const element = document.getElementById('example')
const qobScopedToElement = qob.for(element || document)

// Assuming the element exists, 
//  observation begins at #example instead of document.
qobScopedToElement('.example-child', (records) => { /* ... */ })

Help

See MutationObserver and MutationRecord MDN docs for more information about the MutationObserver API.

Package Sidebar

Install

npm i qob

Weekly Downloads

0

Version

1.0.0

License

MIT

Unpacked Size

13.2 kB

Total Files

6

Last publish

Collaborators

  • pancakeoverflow