This repository has been archived on 2020-09-01. You can view files and clone it, but cannot push or open issues or pull requests.
reactimal/docs/property.md

1.9 KiB

property

A property is a subscribable, scalar value store. It serves as a change deduplicator or the entry point to a logic graph built with computeds or streams.

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

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.

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.

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.

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.