在JavaScript中,events
非常常见,可以称为:
<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";
}
我知道,对于典型的JS函数,我们可以在GO中使用js.Global().Get().Call()
和js.Global().Get().Invoke()
,如:
//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.");
};
}
有什么想法吗?
如果even是可归属变量(例如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
函数;(