Star

Created With

Expressions


The expr() utility allows creating expressions from other callbags:

1linkimport { expr } from 'callbag-common';

2link

3linkconst count = state(0);

4link

5linkconst add = () => count.set(count.get() + 1);

6linkconst color = expr($ => $(count) % 2 ? 'red' : 'green');

7link

8linkrenderer.render(

9link <div onclick={add} style={{ color }}>

10link You have clicked {count} times!

11link </div>

12link).on(document.body);

Playground
1linkimport { expr } from 'callbag-common';

2link

3linkconst a = state(0);

4linkconst b = state(0);

5link

6linkrenderer.render(

7link <>

8link <input _state={a} type='number'/>

9link +

10link <input _state={b} type='number'/>

11link =

12link {expr($ => $(a) + $(b))}

13link </>

14link).on(document.body);

Playground

⚠️ IMPORTANT ⚠️

Be careful to NOT create new callbags inside the function passed to expr():

1link// 🚫 WRONG:

2linkexpr($ => $~(~interval~~~~~~~~(~1000~~~~)~)~ % 2)

3link

4link// ✅ CORRECT:

5linkconst timer = interval(1000)

6linkexpr($ => $(timer) % 2)




linkPassive Tracking

The expr() is re-calculated any time any of the tracked callbags has a new value. You can also passively track callbags, so that their latest value is used without the expression being re-calculated when they have new value:

1linkconst a = state(0);

2linkconst b = state(0);

3link

4linkrenderer.render(

5link <>

6link <input _state={a} type='number'/>

7link +

8link <input _state={b} type='number'/>

9link =

10link {expr(($, _) => $(a) + _(b))} {/* --> b is tracked passively */}

11link </>

12link).on(document.body);

Playground

⚠️ WARNING

Make sure that at least one callbag is actively tracked, as otherwise the expression will never be re-evaluated!




linkDefault Values

The expression might be evaluated while some callbags have not yet emitted values. In that case, undefined is assumed for their value. You can change that by providing a default value to the $() tracking function:

1linkexpr($ => $(a, 0) % 2) // --> assume value 0 when a has not emitted yet


local_library FURTHER READING

expr() is a utility provided by callbag-common package, exported from callbag-expr. Checkout their corresponding docs (here and here) for further information.





Passive TrackingDefault Values

Home Getting Started


Introductionchevron_right

Basicschevron_right

Reactivitychevron_right

Componentschevron_right

In-Depthchevron_right

Metachevron_right