Read & Write Properties
Nodes have properties to which one can read or write a value. It is the most common and basic task when developing a node. Fortunately, it is also incredibly easy.
Read a Property Value
The simpiliest way to read data from a property is to use context.get('<property_name>')
.
count:
datatype: number
default: 1
console.log('Count is', context.get('count'));
Count is 1
Changing a Property
Writing values to a property is also fairly simple, but for more complex values may require a bit more. Primitive datatypes such as text
, number
, and boolean
are easy. More complex datatype like arrays and object require a little more thought, although it depends largely on what is being accomplished.
Writing a Value
The recommended and simpiliest way to write a value to a property is to use context.set('{property_name}', {value})
. This write operation will completely replace the prior value. For non-primitive values like arrays and object this may be less desireable; in those cases a mutate
may be more appropriate. Additionally, some time you need to see the prior value as part of the change operation; in this case you can use the update
context function instead of set
.
context.set('count', 2); // set value to a property
Count before write is 1
Count after write is 2
Update Values
Optionally, if you need to reference the prior value as part of writing a value, it is better to use context.update()
. context.update()
has the form context.update(<property name>, <update function>)
.
context.update('count', (prev) => prev + 1);
Update Object Values
If you are working with objects, you can also do fine-grain updates using context.mutate
. Fine-grain mutations are preferred in reactive systems because we can reactively update the other connected properties in a fine-grained manner; meaning we can only update the part that changed, as opposed to the whole object. context.mutate()
has the form context.mutate(<property name>, <mutate function>)
. Here's an example usage:
context.mutate('obj', (obj) => {
obj.list[0] = '123';
obj.list.push(456);
});