Reactive state library based on the vue.js 2.x observer code
npm install @microlibs/legacy-reactornpm run lint: Lint all typescript files.
npm run format: Format all ts files in the src folder.
npm run commit: Commit using commitzen to ensure commits follow the correct convention.
npm run test: Run all jest tests on files that end with *.spec.ts in the src folder.
npm run cov: Generate and open a test coverage report using jest.
npm run cov:open: Open the generated test coverage report.
npm run doc: Generate and open documentation using typedoc.
npm run doc:open: Open generated documentation.
npm run build: Build the project using the typescript compiler.
npm run version: Generate or update a CHANGELOG.md, bump the package version and create a tag using Standard Version.
npm run prepublish: Automatically runs before the npm publish command and ensures that the code is formatted, tested and built before publishing.
javascript
import { observe } from '@microlibs/legacy-reactor';
const observed = observe({
price: 55.6,
qty: 100,
// Any function in this object is treated as a computed property definition.
total() {
return this.price * this.total;
},
});
console.log(observed.total); // output: 5560
observed.price = 60;
console.log(observed.total); // output: 6000
observed.qty = 50;
console.log(observed.total); // output: 3000
`
$3
Computed properties disable data updates within them to keep your data predictable.
Setting the value of data within a computed property will cause an exception.
`typescript
const observed = observe({
price: 10,
qty: 5,
total() {
// okay
var value = this.price * this.total;
// this line will throw an exception
this.price = 1000;
return value;
},
});
`
Watchers
Watchers are simple functions that get run when the value of an observed property changes.
You can register multiple watchers per property.
`javascript
import { observe, addPropertyWatcher, removePropertyWatcher } from '@microlibs/legacy-reactor';
const observed = observe({
price: 55.6,
qty: 100,
// Any function in this object is treated as a computed property definition.
total() {
return this.price * this.total;
},
});
// The first parameter is an observed object
// The second parameter is the path to the property in the observed data.
// In case of a nested object {nested: {total: 55 }} you would write 'nested.total'.
// The last parameter is the function to be called when the value of total changes.
const watcher = addPropertyWatcher(observed, 'total', (value, oldValue) => {
console.log(value, oldValue);
});
observed.price = 100; // output: 10000 5560
removePropertyWatcher(observed, 'total', watcher);
// No output since the watcher was removed
observed.price = 60.56;
``