xobject-observe

A cross-browser object property observer uses ES6 proxy underneath and with fallback on dirty-checking

Usage no npm install needed!

<script type="module">
  import xobjectObserve from 'https://cdn.skypack.dev/xobject-observe';
</script>

README

xobject-observe

Build Status Coverage Status Deps NPM version Downloads extra

Selenium Browser Matrix

A cross-browser object property observer uses ES6 proxy underneath and with fallback on dirty-checking.

NPM

npm i xobject-observe -S

Browser (for non compatible npm environment)

Include dist/observe.browser.js into your page and use xObjectObserve() function.

Features

  • Uses ES6 proxy and fallback on dirty-checking for old browsers
  • Extensible and configurable detection backends
  • Complete life-cycle management (observe() and observe.stop())
  • Automated cross-browser support through SauceLabs (IE 10+, Chrome 33+, Firefox 33+, Safari 5+)
  • 100% code coverage
  • Available build for non-commonjs environment

Usage

const observe = require('xobject-observe');

// create an empty object and observe it
const obj = observe({}, (property, oldValue, newValue, obj) => {
  console.log('%s (%s -> %s)', property, oldValue, newValue);
})

obj.a = 1; // log: "a (undefined -> 1)" (adding)
obj.a = 2;// log: "a (1 -> 2)" (changing)
obj.b = {c:1}; // log: "b (undefined -> {c:1})" (removing)

observe.stop(obj); // stop observing

Currently supported detection backends

  • es6proxy: (fastest way in JS) leverage ES6 Proxy to detect changes made on an object. No need to configure anything.
  • dirtyChecking: (slow but works everywhere) regulary check if properties of the observed object between the last check (shallow object clone) and now. The comparison is done through a strict equality thus changes on nested objects are not supported. The check interval (in ms) is configurable through observe.config.DIRTYCHECK_DELAY = 1000.

Other backends can easily be setted at runtime as new attributes in observe.methods.

How does it differ from Object.observe?

Object.observe is obsolete. It was deprecated in Chrome 49 and was entirely removed in Chrome 52. xobject-observe offers a cross-browser alternative to it with a slightly easier API.

xobject-observe leverage instead the ES6 Proxy object API underneath for modern browsers and fallback on dirty-checking.

Changelog

Todo:

  • IE9 support
  • IE8 support
  • (bonus) Opera support

Development

  • npm run update: update dependencies
  • npm run changelog: update changelog
  • npm run test-browser: test browser