Skip to content

Commit cd51c2c

Browse files
committed
feat: Add BindEl helper for DOM element wrapping
1 parent 5c80818 commit cd51c2c

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

v1/composition/node.go

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,18 @@ func (e elWrap) Append(nodes ...Node) {
2727
}
2828
}
2929

30+
// BindEl invokes fn with a wrapper exposing Clear and Append helpers for the
31+
// provided element.
32+
func BindEl(el dom.Element, fn func(El)) {
33+
if fn == nil {
34+
panic("composition.BindEl: nil fn")
35+
}
36+
if el.IsNull() || el.IsUndefined() {
37+
return
38+
}
39+
fn(elWrap{el})
40+
}
41+
3042
// Bind selects the first element matching selector and invokes fn with a
3143
// wrapper exposing Clear and Append helpers.
3244
func Bind(selector string, fn func(El)) {
@@ -37,10 +49,7 @@ func Bind(selector string, fn func(El)) {
3749
panic("composition.Bind: nil fn")
3850
}
3951
el := dom.Doc().Query(selector)
40-
if el.IsNull() || el.IsUndefined() {
41-
return
42-
}
43-
fn(elWrap{el})
52+
BindEl(el, fn)
4453
}
4554

4655
// For repeatedly calls fn to generate nodes and appends them to the element

v1/composition/node_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,21 @@ func TestBind(t *testing.T) {
2323
}
2424
}
2525

26+
func TestBindEl(t *testing.T) {
27+
doc := dom.Doc()
28+
doc.Body().SetHTML("<div id='root'><span>old</span></div>")
29+
30+
BindEl(doc.ByID("root"), func(el El) {
31+
el.Clear()
32+
el.Append(Div().Text("new"))
33+
})
34+
35+
root := doc.ByID("root")
36+
if html := root.HTML(); html != "<div>new</div>" {
37+
t.Fatalf("expected <div>new</div>, got %q", html)
38+
}
39+
}
40+
2641
func TestFor(t *testing.T) {
2742
doc := dom.Doc()
2843
doc.Body().SetHTML("<div id='list'></div>")

0 commit comments

Comments
 (0)