0.10.1 • Published 5 months ago

simple-prefs v0.10.1

Weekly downloads
5
License
MIT
Repository
github
Last release
5 months ago

simple-prefs

Provides forward-looking async but simple local storage APIs for which JSON serialization and deserialization is automated, along with a means to supply defaults.

Installation

npm install --save simple-prefs

For older browser support, you may also need core-js-bundle.

Browser

<script type="./node_modules/simple-prefs/dist/index.umd.cjs"></script>

Browser (ESM)

import {SimplePrefs} from './node_modules/simple-prefs/dist/index.esm.js';

Browser (Bundle)

import {SimplePrefs} from 'simple-prefs';

Usage

Basic usage

// This is the simple means for specifying defaults
const defaults = {
  someBoolean: true,
  someNumber: 15.4,
  someString: 'A string!'
};
const prefs = new SimplePrefs({namespace: 'myApp-', defaults});

const currentBooleanPrefValue = await prefs.getPref('someBoolean'); // `true`

// Later
await prefs.setPref('someBoolean', false); // `false` (resolves to old setting)

For a slightly easier approach, you can use the bind method:

const {
  getPref, setPref
} = new SimplePrefs({namespace: 'myApp-', defaults}).bind();

const currentBooleanPrefValue = await getPref('someBoolean'); // `true`

// Later
await setPref('someBoolean', false); // `false` (resolves to old setting)

Listening

You can also listen for storage events.

They can be namespace-specific:

const prefs = new SimplePrefs({namespace: 'myApp-'});

// Returns a StorageEvent: https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent
//  ... but only for storage keys with namespace "myApp-"
prefs.listen((e) => {
  // If `e.key === null` there has been a browser or app `clear` event
  console.log(e.oldValue, e.newValue, e.key, e.storageArea, e.url);
});

Or they can also be specific to a particular key (though this will not listen for clear events):

const prefs = new SimplePrefs({namespace: 'myApp-'});

// Returns a StorageEvent: https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent
//  ... but only for storage keys with namespace "myApp-"
const listener = prefs.listen('myKey', (e) => {
  console.log(
    e.oldValue, e.newValue, e.key === 'myApp-myKey', e.storageArea, e.url
  );
});

You can listen to a previously registered listener:

prefs.unlisten(listener);

You can also unlisten to all listeners:

prefs.unlisten();
0.10.1

5 months ago

0.10.0

5 months ago

0.9.0

3 years ago

0.8.0

3 years ago

0.7.0

3 years ago

0.6.0

4 years ago

0.5.0

5 years ago

0.4.0

5 years ago

0.3.0

5 years ago

0.2.0

5 years ago

0.1.0

5 years ago