Event Binding - addEventListener in Go


This post shows how to do event binding in Go/GopherJS on your browser, i.e., tell the browser to do some actions (i.e., handle the event) when some event occurs. We will use addEventListener method to register the event handler to the event of the specified DOM element. The full code example of this post is on my GitHub.

addEventListener() method

Assume we have the following div element in our HTML

<div id="foo">Click Here</div>

We will attach a click event handler to the div element, and when users click on the div, the text content of the div element will be changed to I am clicked.

JavaScript

var f = document.querySelector("#foo");

f.addEventListener("click", function(e) {
  f.textContent = "I am clicked";
});

GopherJS

The above code in Go/GopherJS is as follows:

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

f := js.Global.Get("document").Call("querySelector", "#foo")

f.Call("addEventListener", "click", func(event *js.Object) {
      f.Set("textContent", "I am clicked")
})

GopherJS + godom

To make your code more readable, we can prettify the above code with godom:

import (
      . "github.com/siongui/godom"
)

f := Document.QuerySelector("#foo")

f.AddEventListener("click", func(e Event) {
      f.SetTextContent("I am clicked")
})

You can add third argument (useCapture, a boolean value) to the addEventListener() method. The default is false is not specified.


References:

[1][Golang] GopherJS Synonyms with JavaScript
[2][GopherJS] Register Event Handler (Event Binding)
[3][Golang] GopherJS DOM Example - Event Binding (addEventListener)