68 lines
1.9 KiB
Markdown

# property
A `property` is a [subscribable](./subscribable.md), scalar value store. It serves as a change
deduplicator or the entry point to a logic graph built with [computed](./computed.md)s or
[stream](./stream.md)s.
Subscribers will only be notified when the value passed to the property is different from the
previously stored value. By default, `property` will use Javascript's identity operator (===) to
determine difference but this is customizable by passing a hash function.
## Usage
### Creation
Creates a property instance and sets its initial value to `true`
```js
const inViewport = prop(true);
```
### Change
Call the property passing in the new value. If the passed value is different from the stored value,
the passed value will be stored and any subscribers will be notified of the change.
```js
inViewport(false);
```
### Read
Call the property with no parameters to receive the stored value.
_NOTE: This use-case is available but discouraged. Instead build a logic graph that uses the
property as an input._
```js
if (inViewport()) {
/* inViewport is truthy */
}
```
### Provide a hash function for storing complex types
When storing a type that is not determined to be equal with an identity operator (===), provide a
hash function to the `hashableProperty` type to create a property that will reduce the passed values
to a value that can be compared with the identity operator before comparison. The passed value will
still be stored unmodified.
```js
function hashSet(_a) {
if (_a instanceof Set) {
return Array.from(_a.keys())
.sort()
.map(k => `${(typeof k).substr(0, 1)}:${encodeURIComponent(k)}/`)
.join('?');
}
return _a;
}
const setProp = hashableProperty(hashSet);
const a = setProp(new Set([1, 2]));
```
In the above example, `hashSet` will be called any time `setProp` receives a new value. The result
of `hashSet` will be compared against the previous hashSet result for the previously stored value.