Reactivity
XylemJS supports reactive programming through the use of reactive primitive called Supplier.
Supplier is any object with following signature:
{ // _ (underscore) method returns the underlying value that this object represents _() { // ... }, // subscribe method stores the callback parameter. // callback is usually called whenever the underlying value changes subscribe(callback) => { // ... }, }
XylemJS provides various function to create Supplier.
- createStore()
- map()
- combineSuppliers()
- combineNamedSuppliers()
- createArrayStore()
Some of them are described below:
createStore(value)
This creates Supplier which also stores the supplied value.
The underscore method accepts a parameter that is used as new value. After the new value has set, if the old value and new value are not identical (i.e. oldValue !== newValue
), the subscribers are notified with the new value.
import createStore from './node_modules/@xylem-js/xylem-js/core/createStore.js'; const name$ = createStore('Foo'); console.log(name$._()); name$.subscribe(v => console.log(v)); name$._('Bar');
The output of above program in console:
Foo Bar
map(supplier, mapper)
This creates Supplier which is derived from other Supplier.
import createStore from './node_modules/@xylem-js/xylem-js/core/createStore.js'; import map from './node_modules/@xylem-js/xylem-js/core/map.js'; const name$ = createStore('Foo'); const greet$ = map(name$, v => `Hello ${v}`); console.log(greet$._()); greet$.subscribe(v => console.log(v)); name$._('Bar');
The output of above program in console:
Hello Foo Hello Bar