从GO WebAssembly调用JavaScript事件

huangapple go评论90阅读模式
英文:

Calling JavaScript event from GO WebAssembly

问题

在JavaScript中,事件非常常见,可以通过以下方式调用:

<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";                   
 });

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

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

我知道在GO中,可以使用js.Global().Get().Call()js.Global().Get().Invoke()来调用典型的JS函数,如下所示:

//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
}

要在GO中添加eventListner,可以按照以下方式进行:

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)

我正在寻找的是,如何在GO中对由JavaScript触发的事件进行响应。

更新

总结一下,我如何编写一个go代码来完成下面的JavaScript代码所做的事情(使用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.");
    };
 }

有什么想法吗?

英文:

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?

答案1

得分: 1

如果你的事件是一个可归因的变量(例如 request.onsuccess = function() { ... }),你可以使用 Set 来定义一个 js.FuncOf,以处理结果,就像处理一个 JavaScript 函数一样,类似于:

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)

别忘了在完成后释放函数(Release);)

英文:

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 从GO WebAssembly调用JavaScript事件

huangapple
  • 本文由 发表于 2021年11月15日 18:35:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/69972999.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定