Using the browser's Document Object Model (DOM), events can be attached to HTML elements by providing an attribute of the event name prefixed with @. For example <div @click='data.HandleClick()'>

The name of the event correspoonds to a regular DOM event as would be provided to addEventListener.

The Go expression provided must be a Go method call. The method name must be exported (begin with an upper case letter). Other Go statements are not currently allowed. The arguments to the function call can be anything valid in Go, including literals.

  1. <div>
  2. <div vg-if='data.Show'>I am here!</div>
  3. <button @click='data.Toggle()'>Toggle me Silly</button>
  4. </div>
  5.  
  6. <script type="application/x-go">
  7. func (data *RootData) Toggle() { data.Show = !data.Show }
  8. type RootData struct {
  9. Show bool
  10. }
  11. </script>
  • The special variable event (of type *vugu.DOMEvent) corresponds to the event data sent to us by the browser. It also provides some useful functionality such as a PreventDefault() method which corresponds to preventDefault
  • For operations that involve blocking (waiting for I/O - such as fetching data from a URL), you should create a goroutine and use event.EventEnv() to acquire a lock before modifying data, and release it afterward.

Important

When your event handler method is called, an exclusive lock is already acquired against the rendering environment. It is released automatically when your handler method exits. Do not block waiting for I/O inside your handler directly, instead use a goroutine. Inside the goroutine (and only inside goroutines, not directly in your handler method) you must use event.EventEnv().Lock() and event.EventEnv().UnlockRender() (or UnlockOnly()) to ensure only one thing is accessing your information at a time. You can also use RLock() and RUnlock() for read-only access from a goroutine. These methods behave exactly as you would expect from RWMutex and if you have never used one of those, now would be a great time to bone up on them.

See Code for an example of using a goroutine to fetch data and locking/unlocking when handling the results.

  • Note that the method call arguments must hash properly with ComputeHash(), as this is needed by Vugu to keep track of its events internally. Most primitive types that just store data are fine, but please, no channels.