Snippets

Patrick Logan GopherJS clock using browser custom element API

You are viewing an old version of this snippet. View the current version.
Revised by Patrick Logan e5d21a0
func defineClock() {
	htmlElement := js.Global.Get("HTMLElement")
	reflect := js.Global.Get("Reflect")
	xclock := js.MakeFunc(func(this *js.Object, arguments []*js.Object) interface{} {
		instance := reflect.Call("construct", htmlElement, make([]interface{}, 0), js.Global.Get("XClock"))
		instance.Set("interval", nil)
		instance.Call("addEventListener", "click", js.MakeFunc(func(this *js.Object, arguments []*js.Object) interface{} {
			if this.Get("interval") == nil {
				this.Call("start")
			} else {
				this.Call("stop")
			}
			return nil
		}))
		return instance
	})
	js.Global.Set("XClock", xclock)
	prototype := xclock.Get("prototype")
	object := js.Global.Get("Object")
	object.Call("setPrototypeOf", prototype, htmlElement.Get("prototype"))
	object.Call("setPrototypeOf", xclock, htmlElement)
	prototype.Set("connectedCallback", js.MakeFunc(func(this *js.Object, arguments []*js.Object) interface{} {
		this.Call("start")
		return this
	}))
	prototype.Set("start", js.MakeFunc(func(this *js.Object, arguments []*js.Object) interface{} {
		this.Call("update")
		update := this.Get("update").Call("bind", this)
		this.Set("interval", js.Global.Call("setInterval", update, 1000))
		return this
	}))
	prototype.Set("stop", js.MakeFunc(func(this *js.Object, arguments []*js.Object) interface{} {
		js.Global.Call("clearInterval", this.Get("interval"))
		this.Set("interval", nil)
		return this
	}))
	prototype.Set("update", js.MakeFunc(func(this *js.Object, arguments []*js.Object) interface{} {
		this.Set("textContent", time.Now().Format(time.RFC1123))
		return this
	}))
	js.Global.Get("customElements").Call("define", "x-clock", xclock)
}
<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>G.U.M.P.</title>
		<meta name="description" content="Example G.U.M.P.">
		<meta name="author" content="Patrick Logan">
		<script src="gump.js"></script>
		<link rel="stylesheet" type="text/css" href="gump.css" />
	</head>
	<body>
		<x-clock></x-clock>
	</body>
</html>