Home > database >  Calling JavaScript event from GO WebAssembly
Calling JavaScript event from GO WebAssembly

Time:11-16

In JavaScript events are vey common that can be called as:


<p id="p_id">
</p><button id="some_id">Click me</button>

var element=document.querySelector("#some_id")
var listener=element.addEventListener('click',function(event){  
     document.querySelector("#p_id").innerHTML = "Hello World";                   
 });

// OR
<p id="p_id">
<button onclick="some_function()">Click me</button>

<script>
function some_function() {
  document.querySelector("#p_id").innerHTML = "Hello World";
}

I aware with typical JS functions, we can use js.Global().Get().Call() and js.Global().Get().Invoke() in GO, as:

//go:build js && wasm

package main

import (
    "syscall/js"
)

var (
    document js.Value
)

func init() {
    document = js.Global().Get("document")

}

func main() {
    c := make(chan int) // channel to keep the wasm running, it is not a library as in rust/c/c  , so we need to keep the binary running
    
    alert := js.Global().Get("alert")
    alert.Invoke("Hi")    
    
    h1 := document.Call("createElement", "h1")
    h1.Set("innerText", "This is H1")
    h1.Get("style").Call("setProperty", "background-color", "blue")

    <-c
}

To add eventListner from GO, I know we can do it as:

var cb js.Func
cb = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
    fmt.Println("button clicked")
    cb.Release() // release the function if the button will not be clicked again
    return nil
})
js.Global().Get("document").Call("getElementById", "myButton").Call("addEventListener", "click", cb)

What I'm looking for, is how to response from GO to the even that is triggered in JavaScript.

UPDATE

To wrap up, how can I write a go code to do the same of the JavaScript code below (Which is using IndexedDB API):

function remove() {
    var request = db.transaction(["employee"], "readwrite")
    .objectStore("employee")
    .delete("00-03");
    
    request.onsuccess = function(event) {
       alert("Kenny's entry has been removed from your database.");
    };
 }

Any thought?

CodePudding user response:

If your even is an attributable variable (e.g. request.onsuccess = function() { ... }) you can use Set to define a js.FuncOf to handle the result as a javascript function would, something like:

req := js.Global().Get("db").Call("transaction").Call("objectStore").Call("delete")
var f js.Func
f = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
    defer f.Release()

    js.Global().Call("alert", "Kenny's entry has been removed from your database.")
    return nil
})
req.Set("onsuccess", f)

Don't forget to Release the function once you're done ;)

  •  Tags:  
  • go
  • Related