0.1.0 • Published 6 years ago

propserver v0.1.0

Weekly downloads
17
License
MIT
Repository
github
Last release
6 years ago

Responsive property observation for JavaScript

propserver Travis

What is it good for

Sometimes you want to be notified on each frame about a property change so you can handle things in a more responsive way.
Consider when you have an element on a page, and you want to check its offsetTop property so you know when the element is inside/outside the viewport.
You can observe the element offetTop with propserver and be notified when it changes.

This module should be used on the client side

Install

Install via npm with

$ npm install --save propserver

What makes it responsive

As you know, calling requestAnimationFrame to request an animation frame help us to optimize operations and queries on the DOM, since the browser waits for the next frame to render in order to run our callbacks. However, when requesting many animation frames synchronously, the browser will stack all the repeated request animation frames.
When you creates more than one observer, all animation frames are managed in a timeline so only one requestAnimationFrame gets called.

Creating property observer

import { createObserver } from "propserver";

// get notified when $anything.offsetTop is changes
function callback(value, prevValue) {
    console.log(value, prevValue);
}

// create property ovserver
const observer = createObserver($anything, "offsetTop", callback);

// start observing for $anything.offsetTop changes
observer.observe();

// disconnect the observer when you finish
observer.disconnect();

API

createObserver(target, property, callback)

Factory function to create property observer.

NameTypeRequiredDescription
targetObjecttruethe target that holds the property
propertyStringtruethe property to observe on the target
callbackFunctiontruea callback function to be called when the target property changes function (newValue, oldValue) {}

createObserver(propertyGetter, callback)

NameTypeRequiredDescription
property getterFunctiontruea function to get the property
callbackFunctiontruea callback function to be called when the property changes function (newValue, oldValue) {}

The second option to create observer with property getter function. this method is for cases where you want to run a function to get the value, like where the property is not a direct property of your target.
Here is a property getter example:

() => {
    const { top } = target.getBoundingClientRect();
    return top;
}

License

This project is licensed under the MIT License - see the LICENSE file for details

0.1.0

6 years ago

0.0.8

6 years ago

0.0.7

6 years ago

0.0.6

6 years ago

0.0.4

6 years ago

0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago