local-motive
A small but powerful TypeScript/ES5 library that simplifies the use of HTML5 Web Storage APIs in your models
Installation
To install Local Motive, run:
$ npm install local-motive --save
Usage
Local Motive provides @LocalStorage
and @SessionStorage
decorators that handle storage of model and nested model changes. To use them, just extend the provided LocalModel
abstract class.
LocalModel
requires a storagePath
field, which is used to support storing changes to fields and nested models. It should be provided in the constructor of your derived model class. In addition, LocalModel
provides a subpath()
method for use in generating storage paths for nested models. See the example below.
// person.model.ts // ;;
// phone.model.ts // ;
Now, when you modify values on your models, including nested models, the data will be persisted automatically.
This is especially useful if you're using a framework like Angular, where you can bind directly to locally-stored models in your views:
// demo.component.ts // ;;
Other Features
Decorators
The @LocalStorage
and @SessionStorage
decorators have many more features, like:
- Support for non-string types like number, object, array, and null
- Custom storage key
- Default value
- Custom serialization and deserialization
- Support for inherited properties
For more info, see the decorators source. For additional usage examples, see the test spec.
LocalModel
LocalModel
provides the following interface and can even be used without decorators, if desired:
For usage examples, see the test spec.
A Word of Caution with Initialized Fields
While fields that have initial values can be decorated with the @LocalStorage
or @SessionStorage
decorators, the outcome will likely not be the desired one. This is because an initial value will overwrite any value in storage for a given decorated field. To provide an initial value for a decorated field that will only apply if no value is currently stored, use the defaultValue
parameter in your decorator. See the decorators source for more info.
License
MIT © Andrew Meyer