Skip to content

Commit f3c0f86

Browse files
committed
chore: Refactor event listener example using Composition APIs
1 parent e082c3e commit f3c0f86

File tree

2 files changed

+18
-17
lines changed

2 files changed

+18
-17
lines changed

docs/examples/components/event_listener_component.go

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,30 +5,31 @@ package components
55
import (
66
_ "embed"
77

8+
"github.com/rfwlab/rfw/v1/composition"
89
core "github.com/rfwlab/rfw/v1/core"
9-
events "github.com/rfwlab/rfw/v1/events"
1010
)
1111

1212
//go:embed templates/event_listener_component.rtml
1313
var eventListenerComponentTpl []byte
1414

1515
func NewEventListenerComponent() *core.HTMLComponent {
1616
c := core.NewComponent("EventListenerComponent", eventListenerComponentTpl, nil)
17-
// Always start from zero to avoid residual persisted values.
18-
c.Store.Set("clicks", float64(0))
19-
c.SetOnMount(func(cmp *core.HTMLComponent) {
20-
btn := cmp.GetRef("clickBtn")
21-
ch := events.Listen("click", btn.Value)
22-
go func() {
23-
for range ch {
24-
switch v := cmp.Store.Get("clicks").(type) {
25-
case float64:
26-
cmp.Store.Set("clicks", v+1)
27-
case int:
28-
cmp.Store.Set("clicks", float64(v)+1)
29-
}
30-
}
31-
}()
17+
cmp := composition.Wrap(c)
18+
19+
// Register event handler before mount so the template can bind it.
20+
cmp.On("increment", func() {
21+
switch v := c.Store.Get("clicks").(type) {
22+
case float64:
23+
c.Store.Set("clicks", v+1)
24+
case int:
25+
c.Store.Set("clicks", v+1)
26+
default:
27+
c.Store.Set("clicks", 1)
28+
}
3229
})
30+
31+
// Initialize store on mount.
32+
cmp.SetOnMount(func(*core.HTMLComponent) { c.Store.Set("clicks", 0) })
33+
3334
return c
3435
}
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<root>
22
<div class="p-4 pt-0">
33
<h2 class="text-xl font-bold mb-4">Event Listener Component</h2>
4-
<button [clickBtn] class="px-4 py-2 border border-gray-300 dark:border-zinc-700 bg-lightbg dark:bg-darkbg text-black dark:text-white font-semibold rounded-full hover:bg-white hover:text-red-600 transition">Click me</button>
4+
<button class="px-4 py-2 border border-gray-300 dark:border-zinc-700 bg-lightbg dark:bg-darkbg text-black dark:text-white font-semibold rounded-full hover:bg-white hover:text-red-600 transition" @on:click:increment>Click me</button>
55
<p class="mt-4">Clicks: @store:app.default.clicks</p>
66
</div>
77
</root>

0 commit comments

Comments
 (0)