diff --git a/Makefile b/Makefile index 67c6ca5..c6089b2 100644 --- a/Makefile +++ b/Makefile @@ -70,6 +70,12 @@ vecty: clean cp ./vecty/index.html ./html/index.html cp $$(go env GOROOT)/misc/wasm/wasm_exec.js ./html/wasm_exec.js +.PHONY: export +export: clean + GOOS=js GOARCH=wasm go build -o ./html/test.wasm ./export/main.go + cp ./export/index.html ./html/index.html + cp $$(go env GOROOT)/misc/wasm/wasm_exec.js ./html/wasm_exec.js + .PHONY: test test: GOOS=js GOARCH=wasm go test -v ./test/ diff --git a/README.md b/README.md index b0de495..4f48a3e 100644 --- a/README.md +++ b/README.md @@ -110,3 +110,7 @@ bitcoin price. An example of a [Vecty](https://github.com/gopherjs/vecty) application automatically translating the input textbox to rendered markdown. + +### Export + +An example of exporting a Go function to JavaScript. diff --git a/export/index.html b/export/index.html new file mode 100644 index 0000000..dd13529 --- /dev/null +++ b/export/index.html @@ -0,0 +1,47 @@ + + + + + + + Go wasm + + + + + + + + + +
+ + + \ No newline at end of file diff --git a/export/main.go b/export/main.go new file mode 100644 index 0000000..3e3dab3 --- /dev/null +++ b/export/main.go @@ -0,0 +1,27 @@ +package main + +import ( + "syscall/js" +) + +var document js.Value + +func init() { + document = js.Global().Get("document") +} + +func main() { + document.Set("appendText", js.FuncOf(appendText)) + + // Prevent main from exiting + select {} +} + +func appendText(_ js.Value, _ []js.Value) interface{} { + msg := document.Call("getElementById", "input").Get("value").String() + + p := document.Call("createElement", "p") + p.Set("innerHTML", msg) + document.Call("getElementById", "target").Call("appendChild", p) + return nil +}