10

[Golang] GopherJS DOM Example - Event Binding (addEventListener)

 2 years ago
source link: http://siongui.github.io/2016/01/11/gopherjs-dom-example-event-binding-addEventListener/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Source Code

First we write a simple HTML for our demo:

index.html | repository | view raw

<!doctype html>
<html>
<head>
  <title>GopherJS DOM example - Event Binding (addEventListener)</title>
</head>
<body>
  <div id="foo">Click Me</div>
  <script src="demo.js"></script>
</body>
</html>

We will attach an onclick event handler to the div element whose id is foo. When users click the div element, the content of the div element will be changed, and print a message on the browser console.

bind.go | repository | view raw

package main

import "honnef.co/go/js/dom"

func main() {
	d := dom.GetWindow().Document()
	h := d.GetElementByID("foo")

	h.AddEventListener("click", false, func(event dom.Event) {
		event.PreventDefault()
		h.SetInnerHTML("I am Clicked")
		println("This message is printed in browser console")
	})
}

As the above code show, the event registration is almost the same as JavaScript counterpart. The println will print messages on browser console, which is the same as console.log in JavaScript. Now compile the Go code to JavaScript by:

$ gopherjs build bind.go -o demo.js

Put demo.js together with the index.html in the same directory and open the index.html with your browser. You will see the text Click Me in the browser window. Open your browser console, click the text, you will see the text becomes I am Clicked and the message This message is printed in browser console. is printed on the console.

See Also [GopherJS] Register Event Handler (Event Binding)


Tested on: Ubuntu Linux 15.10, Go 1.5.2.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK