[GopherJS] this Keyword


Show how to access/use this keyword via GopherJS.

In the following demo, move mouse on the word, and the color of the word will become red.

Demo

Source code: use MakeFunc to use this keyword.

index.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>GopherJS Access this Keyword Demo</title>
</head>
<body>

<div id="container">
  <span>Manopubbaṅgamā</span> <span>dhammā</span>, <span>manoseṭṭhā</span>
  <span>manomayā</span>; <span>Manasā</span> <span>ce</span>
  <span>paduṭṭhena</span>, <span>bhāsati</span> <span></span>
  <span>karoti</span> <span></span>; <span>Tato</span> <span>naṃ</span>
  <span>dukkhamanveti</span>, <span>cakkaṃva</span> <span>vahato</span>
  <span>padaṃ</span>.
</div>

<script src="app.js"></script>
</body>
</html>
app.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
	"github.com/gopherjs/gopherjs/js"
)

var onWordMouseOver = js.MakeFunc(func(this *js.Object, arguments []*js.Object) interface{} {
	this.Get("style").Set("color", "red")
	return nil
})

var onWordMouseOut = js.MakeFunc(func(this *js.Object, arguments []*js.Object) interface{} {
	this.Get("style").Set("color", "")
	return nil
})

func main() {
	spans := js.Global.Get("document").Call("getElementById", "container").Call("querySelectorAll", "span")
	// access individual span
	length := spans.Get("length").Int()
	for i := 0; i < length; i++ {
		span := spans.Call("item", i)
		span.Set("onmouseover", onWordMouseOver)
		span.Set("onmouseout", onWordMouseOut)
	}
}

References:

[1]GopherJS - A compiler from Go to JavaScript (GitHub, GopherJS Playground, godoc)
[2]GitHub - siongui/gopherjs-tooltip: Tooltip in Go. Compiled to JavaScript via GopherJS