Skip to content

Commit

Permalink
Add Mounter event interface, complements Unmounter
Browse files Browse the repository at this point in the history
Provides support for a `Mount()` event handler, fired when a component
is attached to the DOM.
  • Loading branch information
pdf committed Jan 27, 2017
1 parent 34ae770 commit b50ec7c
Showing 1 changed file with 31 additions and 3 deletions.
34 changes: 31 additions & 3 deletions dom.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,14 @@ type Component interface {
Context() *Core
}

// Mounter is an optional interface that a Component can implement in order
// to receive component mount events.
type Mounter interface {
// Mount is called after the component has been mounted, after the DOM
// element has been added.
Mount()
}

// Unmounter is an optional interface that a Component can implement in order
// to receive component unmount events.
type Unmounter interface {
Expand Down Expand Up @@ -164,6 +172,7 @@ func (h *HTML) restoreHTML(prev *HTML) {
continue
}
h.Node.Call("appendChild", nextChildRender.Node)
doMount(nextChild)
continue
}
prevChild := prev.children[i]
Expand All @@ -177,7 +186,9 @@ func (h *HTML) restoreHTML(prev *HTML) {
if doRestore(prevChild, nextChild, prevChildRender, nextChildRender) {
continue
}
doUnmount(prevChild)
replaceNode(nextChildRender.Node, prevChildRender.Node)
doMount(nextChild)
}
for i := len(h.children); i < len(prev.children); i++ {
prevChild := prev.children[i]
Expand All @@ -186,9 +197,7 @@ func (h *HTML) restoreHTML(prev *HTML) {
prevChildRender = prevChild.(Component).Context().prevRender
}
removeNode(prevChildRender.Node)
if u, ok := prevChild.(Unmounter); ok {
u.Unmount()
}
doUnmount(prevChild)
}
}

Expand Down Expand Up @@ -261,6 +270,7 @@ func (h *HTML) Restore(old ComponentOrHTML) {
continue
}
h.Node.Call("appendChild", nextChildRender.Node)
doMount(nextChild)
}
}

Expand Down Expand Up @@ -300,7 +310,9 @@ func Rerender(c Component) {
return
}
if prevRender != nil {
doUnmount(c)
replaceNode(nextRender.Node, prevRender.Node)
doMount(c)
}
}

Expand Down Expand Up @@ -350,10 +362,12 @@ func RenderBody(body Component) {
if doc.Get("readyState").String() == "loading" {
doc.Call("addEventListener", "DOMContentLoaded", func() { // avoid duplicate body
doc.Set("body", nextRender.Node)
doMount(body)
})
return
}
doc.Set("body", nextRender.Node)
doMount(body)
}

// SetTitle sets the title of the document.
Expand All @@ -368,3 +382,17 @@ func AddStylesheet(url string) {
link.Set("href", url)
js.Global.Get("document").Get("head").Call("appendChild", link)
}

// doMount calls the Mount function on Mounter components
func doMount(h ComponentOrHTML) {
if m, ok := h.(Mounter); ok {
m.Mount()
}
}

// doUnmount calls the Unmount function on Unmounter components
func doUnmount(h ComponentOrHTML) {
if u, ok := h.(Unmounter); ok {
u.Unmount()
}
}

0 comments on commit b50ec7c

Please sign in to comment.