Eval Commands

Now that we've learned how about events/commands, I want to highlight a few useful commands.

One in particular is EvalCommands, which allows you to evaluate any command against any element just by referencing it in Go.

Referencing an element directly

Example: Setting the text of an element on click of another element

Copy
 1func MyComponent(ctx *h.RequestContext) *h.Element {
 2	text := h.Pf("Text Before")
 3	return h.Div(
 4		h.Button(
 5			h.Text("Toggle Text"),
 6			h.OnClick(
 7				js.EvalCommands(
 8					text,
 9					js.ToggleText("Text Before", "Text After"),
10				),
11			),
12		),
13		text,
14	)
15}

We are calling js.EvalCommands with the text variable and the command to toggle the text of the element.

This always you to run any commands against any element, without having to query for it via a selector.

View the demo for more details on what this could be used for.

Using a selector

If needed, you can query by selector

Copy
 1	
 2func MyComponent(ctx *h.RequestContext) *h.Element {
 3	text := h.Pf("Text Before", h.Id("my-element"))
 4	return h.Div(
 5		h.Button(
 6			h.Text("Toggle Text"),
 7			h.OnClick(
 8				js.EvalCommandsOnSelector(
 9					"#my-element",
10					js.ToggleText("Text Before", "Text After"),
11				),
12			),
13		),
14		text,
15	)
16}