在 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
}
要從eventListnerGO添加,我知道我們可以這樣做:
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.");
};
}
任何想法?
uj5u.com熱心網友回復:
如果你的 even 是一個可歸因變數(例如request.onsuccess = function() { ... }),你可以使用Set定義 ajs.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該功能;)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358284.html
標籤:走
上一篇:如何使用js.Value作為js.Global().Get的引數
下一篇:如何從go中的大json獲取資料
