UseValue Reference

Table of contents


Introduction

The UseValue class is intended to delay the resolution of the value of an object's key until a later time. It is used at the time of object creation to substitute for the value of a key (e.g., key: new UseValue(...)). The actual value is then resolved by calling UseValue.resolveAll() at a later time. There are at least two use cases: References to data in other objects that may not yet be created when the referencing object is created, or the value of this key is based on other keys in the referencing object and, therefore, this value is not yet available without repeating the possibly complex value.

Here's a simple example:

const foo = {
	a: 1,
	b: useValue((obj, key) => obj.a + 1),
}
UseValue.resolveAll(foo);

While this example is trivial, it illustrates a use case that happens often in creating aircraft data in aircraft performance apps.

When it's time to resolve an object (perhaps after the app is loaded or initialization is complete), you can call UseValue.resolveAll(obj) to look for any keys with a UseValue instance as a value and resolve them by calling the resolve() method and sets obj[key] to the returned value.

Subclass UseValue to allow customized references.


Constructor

Syntax

new UseValue(resolverFn)
useValue(resolverFn)

Constructs a new UseValue instance. resolverFn is a function to call when the reference is resolved. The function is passed the containing object and the key to be resolved as parameters and returns the new desired property. The function is called by the resolve() method, by default, and returns the new value, which is used to set the value of the property in the object.

The useValue() function is a factory function that returns a new UseValue instance.

Parameters


Instance methods

resolve()

resolve(obj)

Calls the stored resolverFn() and returns the result. The method allows subclasses to modify resolution.

Parameters

Return value

Any type. The value that is returned by calling the resolverFn().


UseValue.resolveAll()

UseValue.resolveAll(obj)
UseValue.resolveAll(obj, contextObj)

Enumerates all the enumerable own keys in obj and calls the resolve() method on each key that contains a UseValue instance. All nested plain objects are also recursively resolved. It returns the resolved object, obj.

If contextObj is provided, it will be passed to all calls to the resolverFn() as the contextObj argument. Otherwise, the contextObj argument is the value of obj.

Parameters

Return value

The resolved object.