Hi ,
how can i create button with a simpler counter, that just adds 1 to a field every time its used
Hi ,
how can i create button with a simpler counter, that just adds 1 to a field every time its used
Try this code:
\define increment(field:counter)
<$action-setfield $field=$field$ $value={{{ [all[current]get[$field$]!is[blank]else[0]add[1]] }}}/>
\end
;myfield:
:{{!!myfield}}
<$button actions=<<increment myfield>>>
+1
</$button>
In this example, the field’s name is myfield
but you can change it to whatever you want (default name: counter
).
The trick is:
actions
parameter (optional)<$action-setfield>
widget to define the field’s value$value=...
of the fieldUsing the actions
parameter and a filter is needed to defer the evaluation of the new value until the button is pressed, although widgets like <$button>
are usually evaluated only once when the tiddler is rendered.
My reference for this kind of code is @EricShulman’s excellent explanation here.
Fred
This is a neat little button.
One modification I made was changing the +1 to {{!!myfield}}
so I could watch it change every time I clicked it.
Thank you Fred
this works, i have to admit i am really struggling with macros, but i get everything you put, except for the “counter” paramter, how does it fit in the whole macro ?
sorry if i am asking a stupid question
In the macro definition, the field:counter
part means the macro expects a parameter, named field
, and this parameter has a default value of counter
. This default value could have been anything, generally I try to choose the most used value as the default.
As a result, this macro call:
<<increment counter>>
this one:
<<increment field:counter>>
and this one:
<<increment>>
produce the same result: generate an action-setfield widget that increments a field named counter
.
In my example, this is absolutely useless, as the macro and the button are in the same tiddler, so the macro shouldn’t have any parameter and could directly work on the myfield
field like this:
\define increment()
<$action-setfield $field=myfield $value={{{ [all[current]get[myfield]!is[blank]else[0]add[1]] }}}/>
\end
But I prefer when my code is more flexible so I often use parameters, with default values to simplify the most frequent use-cases. It also allows to promote the macro as a global macro by moving its definition in another tiddler tagged $:/tags/Macro
, and then use it in many tiddlers with the chosen field name.
Fred
Thank you Fred for the explanation , makes sense