Skip to content

Commit 57d82a1

Browse files
committed
finished documenting Anonymous Components
1 parent 0b85919 commit 57d82a1

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

readme.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -993,10 +993,66 @@ In short, selective reaction states that only the views that depend on a state w
993993
##### Anonymous Components
994994
Sometimes a state change should not cause a component to rerender in the application. For example, consider a Count state. When the Count state changes, you only want to rerender the number, not the whole component. In that case, use anonymous components.
995995

996+
In OpenScript.Js, the `v` function, representing `valueOf` is used to create an anonymous component. The `v` indicates that you only want to use the value of a state. It passes the value of the state to a provided callback function which should return an `OSM` or a `string`. By default, it returns the value of the state.
997+
996998
*Syntax*
997999
```js
9981000
v(state, callback(value) => OSM | string);
1001+
```
1002+
1003+
*Usage*
1004+
```js
1005+
let counter = state(0);
1006+
1007+
function Clock(...args) {
1008+
return h.div(
1009+
{class: 'd-flex mb-3'},
1010+
h.span('I will not rerender when counter change'),
1011+
1012+
v(counter), // counter.value --> will change when counter value changes
1013+
1014+
...args
1015+
);
1016+
}
1017+
1018+
h.Clock({
1019+
parent: root,
1020+
$class: 'd-block',
1021+
});
1022+
1023+
// change counter value
1024+
setTimeout(() => counter.value++, 1000);
1025+
```
1026+
You can pass a callback function to the `v` function and return a formatted string. For example, returning the time in hours:minutes:seconds.
1027+
1028+
```js
1029+
function Clock(...args) {
1030+
return h.div(
1031+
{class: 'd-flex mb-3'},
1032+
h.span('I will not rerender when counter change'),
1033+
1034+
v(counter, (value) => {
1035+
let sec = value;
1036+
let hour = Math.floor(sec / 3600);
1037+
sec %= 3600;
1038+
1039+
let minute = Math.floor(sec / 60);
1040+
sec %= 60;
1041+
1042+
hour = Math.floor(hour / 10) === 0 ? `0${hour}` : hour;
1043+
minute = Math.floor(minute / 10) === 0 ? `0${minute}` : minute;
1044+
sec = Math.floor(sec / 10) === 0 ? `0${sec}` : sec;
1045+
1046+
let time = `${hour}:${minute}:${sec}`;
1047+
1048+
return time;
1049+
}),
1050+
1051+
...args
1052+
);
1053+
}
9991054
```
1055+
> You can even return a full `OSM` from the `v` function.
10001056
10011057
##### Component Events
10021058
###### Listening to Internal Events

0 commit comments

Comments
 (0)