Skip to content

Latest commit

 

History

History
113 lines (84 loc) · 3.05 KB

README.md

File metadata and controls

113 lines (84 loc) · 3.05 KB

@smoovy/observer

Version Size

Easily observe states of HTML elements and the viewport.

Installation

npm install --save @smoovy/observer

Why?!

Operations like window.innerWidth and element.offsetTop will have an impact on the performance if not used properly. So this package is useful to avoid layout thrashing by batching all of the expensive calls together and only executing them if needed.

Usage

The observer is separated into two main components. The ViewportObserver and the ElementObserver.

Observing the viewport (a.k.a. window)

import { ViewportObserver } from '@smoovy/observer';

const listener = ViewportObserver.changed(state => {
  console.log(`The viewport size is ${state.width}x${state.height}`);
});

To remove the listener you can simply call the remove method:

listener.remove();

The viewport observer's target is always the current window object

Throttling the change listener calls

This will throttle the changed callback to 100ms:

ViewportObserver.changed((state) => {}, 100);

Updating the viewport manually

ViewportObserver.update();

Accessing the state at any time

const state = await ViewportObserver.state;

When does a viewport change occur?

The change gets called everytime the user triggers the resize event on the window element. The ViewportObserver also makes sure to emit only on the next animation frame.

Observing an element

By observing an element you automatically create a state inside the ElementObserver. This will be your reference to the current state of the element:

import { ElementObserver } from '@smoovy/observer';

const element = document.querySelector('#test');
const state = ElementObserver.observe(element);

Listening/Unlistening for element changes

const listener = state.changed(state => {
  console.log('The element: ', state.element);
  console.log('Element size: ', state.size);
  console.log('Element page offset: ', state.offset);
});

// Stop listening
listener.remove();

Changes occur when the ViewportObserver changes or the MutationObserver detects changes inside the document.documentElement

Throttling the change listener calls

This will throttle the changed callback to 100ms:

state.changed((state) => {}, 100);

Updating the element state manually

state.update();

Removing the element state from the observer

state.destroy();

Current issues

Currently there is a circular dependency warning. This will be fixed in the future, but it shouldn't affect the API.

Development commands

// Serve with parcel
npm run serve

// Build with rollup
npm run build

// Run Jest unit tests
npm run test

// Run TSLinter
npm run lint

License

See the LICENSE file for license rights and limitations (MIT).