# dexie-observable

> Addon to Dexie that makes it possible to observe database changes no matter if they occur on other db instance or other window.

Latest version **4.0.1-beta.13** (published 2023-01-17) · Apache-2.0 license · 0 weekly downloads

## Install

```sh
npm install dexie-observable
pnpm add dexie-observable
yarn add dexie-observable
bun add dexie-observable
```

## Health

**Score 50/100 (C)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities; high maintenance score; high quality score; popular repo.

Warnings: low downloads.

Negative: abandoned.

## Facts

| | |
|---|---|
| Version | 4.0.1-beta.13 |
| Published | 2023-01-17 |
| First published | 2016-03-07 |
| Weekly downloads | 0 |
| License | Apache-2.0 |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 0 |
| Unpacked size | 314.6 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 14597 |
| Author | David Fahlander |
| Maintainers | dfahlander |
| Keywords | indexeddb, browser, dexie, addon |

## Links

- npm: https://www.npmjs.com/package/dexie-observable
- Repository: https://github.com/dexie/Dexie.js
- Homepage: https://dexie.org
- Issues: https://github.com/dexie/Dexie.js/issues
- npm.io page: https://npm.io/package/dexie-observable

## Alternatives

- [@opentelemetry/exporter-zipkin](https://npm.io/package/@opentelemetry/exporter-zipkin.md) — 14.8M weekly downloads
- [pusher-js](https://npm.io/package/pusher-js.md) — 2.0M weekly downloads
- [browserify](https://npm.io/package/browserify.md) — 1.7M weekly downloads
- [sqs-consumer](https://npm.io/package/sqs-consumer.md) — 1.7M weekly downloads
- [@sanity/eventsource](https://npm.io/package/@sanity/eventsource.md) — 930.8K weekly downloads

## Recent versions

- 4.0.1-beta.13 (latest) — 2023-01-17
- 4.0.0-beta.13 (next) — 2022-04-01
- 4.0.0-beta.12 — 2022-04-01
- 3.0.0-beta.11 — 2021-05-28
- 3.0.0-beta.10 — 2020-10-16
- 3.0.0-beta.9 — 2020-09-07
- 1.0.0-beta.8 — 2020-07-30
- 1.0.0-beta.7 — 2020-05-07
- 1.0.0-beta.6 — 2020-01-29
- 1.0.0-beta.5 — 2018-10-23
- 1.0.0-beta.4 — 2017-09-05
- 1.0.0-beta.3 — 2017-01-31
- 1.0.0-beta.2 — 2017-01-28
- 1.0.0-beta.1 — 2017-01-27
- 0.9.2 — 2016-12-22
- … 12 more at https://npm.io/package/dexie-observable/versions

## README

# Dexie.Observable.js

Observe changes to database - even when they happen in another browser window.

### Install
```
npm install dexie --save
npm install dexie-observable --save
```

### Use
```js
import Dexie from 'dexie';
import 'dexie-observable';

// Use Dexie as normally - but you can also subscribe to db.on('changes').

```

#### Usage with existing DB

In case you want to use Dexie.Observable with your existing database, you will have to do a schema upgrade. Without it Dexie.Observable will not be able to properly work.

```javascript
import Dexie from 'dexie';
import 'dexie-observable';

var db = new Dexie('myExistingDb');
db.version(1).stores(... existing schema ...);

// Now, add another version, just to trigger an upgrade for Dexie.Observable
db.version(2).stores({}); // No need to add / remove tables. This is just to allow the addon to install its tables.
```

### Dependency Tree

 * [Dexie.Syncable.js](https://dexie.org/docs/Syncable/Dexie.Syncable.js)
   * **Dexie.Observable.js**
     * [Dexie.js](https://dexie.org/docs/Dexie/Dexie.js)
       * [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API)

### Source

[Dexie.Observable.js](https://github.com/dexie/Dexie.js/blob/master/addons/Dexie.Observable/src/Dexie.Observable.js)

### Description

Dexie.Observable is an add-on to Dexie.js makes it possible to listen for changes on the database even if the changes are made in a foreign window. The addon provides a "storage" event for IndexedDB, much like the storage event (onstorage) for localStorage.

In contrary to the [Dexie CRUD hooks](https://dexie.org/docs/Tutorial/Design#the-crud-hooks-create-read-update-delete), this event reacts not only on changes made on the current db instance but also on changes occurring on db instances in other browser windows. <u>This enables a Web Apps to react to database changes and update their views accordingly.</u>

Dexie.Observable is also the base of [Dexie.Syncable.js](https://dexie.org/docs/Syncable//Dexie.Syncable.js) - an add-on that enables two-way replication with a remote server.

### Extended Methods, Properties and Events

#### UUID key generator
When defining your stores in [Version.stores()](https://dexie.org/docs/Version/Version.stores()) you may use the $$ (double dollar) prefix to your primary key. This will make it auto-generated to a UUID string. See sample below.

#### Dexie.Observable.createUUID()
A static method added to Dexie that creates a UUID. This method is used internally when using the $$ prefix to primary keys. To change the format of $$ primary keys, just override Dexie.createUUID by setting it to your desired function instead.

#### db.on('changes') event
Subscribe to any database changes no matter if they occur locally or in other browser window.

Parameters to your callback:

<table>
<tr><td>changes : Array&lt;<a href="https://dexie.org/docs/Observable/Dexie.Observable.DatabaseChange">DatabaseChange</a>&gt;</td><td>Array of changes that have occured in database (locally or in other window) since last time event was triggered, or the time of starting subscribing to changes.</td></tr>
<tr><td>partial: Boolean</td><td>True in case the array does not contain all changes. In this case, your callback will soon be called again with the additional changes and partial=false when all changes are delivered.</td></tr>
</table>

#### Example (here we're using plain ES6 script tags):
```html
<html>
    <head>
    <script src="dexie.min.js"></script>
    <script src="dexie-observable.min.js"></script> <!-- Enable DB observation -->
    <script>
        var db = new Dexie("ObservableTest");
        db.version(1).stores({
            friends: "$$uuid,name"
        });
        db.on('changes', function (changes) {
            changes.forEach(function (change) {
                switch (change.type) {
                    case 1: // CREATED
                        console.log('An object was created: ' + JSON.stringify(change.obj);
                        break;
                    case 2: // UPDATED
                        console.log('An object with key ' + change.key + ' was updated with modifications: ' + JSON.stringify(change.mods));
                        break;
                    case 3: // DELETED
                        console.log('An object was deleted: ' + JSON.stringify(change.oldObj);
                        break;
            });
        });
        db.open();
        // Make an initial put() - will result in a CREATE-change:
        db.friends.put({name: "Kalle"}).then(function(primKey) {
            // Call put() with existing primary key - will result in an UPDATE-change:
            db.friends.put({uuid: primKey, name: "Olle"}).then (function () {
                // Call delete() will result in a DELETE-change:
                db.friends.delete(primKey);
            });
        });

        // Result that will be logged:
        // An object was created: {"uuid": "23bada36-d27a-4e78-a978-1ab3c4129cd0", name: "Kalle"}
        // An object with key: 23bada36-d27a-4e78-a978-1ab3c4129cd0 was updated with modifications: {"name": "Olle"}
        // An object was deleted: {"uuid": "23bada36-d27a-4e78-a978-1ab3c4129cd0", name: "Olle"}
    </script>
    </head>
    <body>
    </body>
</html>
```

---
_Source: https://npm.io/package/dexie-observable · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
