嘗試使用 GO WebAssembly 訪問瀏覽器 IndexedDB,使用以下代碼我能夠創建 ibdexedDB,但是在嘗試使用js.Global().Get(dbx)甚至嘗試訪問它時出現錯誤this.result
//go:build js && wasm
package main
import (
"fmt"
"syscall/js"
)
var dbOk, dbErr js.Func
var db js.Value
func main() {
fmt.Println("Hello WASM")
db = js.Global().Get("indexedDB").Call("open", "Database", 1)
dbOk = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
defer dbOk.Release()
/* Here I've an error */
dbx := this.result
fmt.Println("this is: ", dbx)
/**********************/
js.Global().Call("alert", "ok.")
return nil
})
db.Set("onsuccess", dbOk)
dbErr = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
defer dbErr.Release()
js.Global().Call("alert", "sorry.")
return nil
})
db.Set("onerror", dbErr)
/* This line is wrong, can not access `db` */
js.Global().Get(dbx).Call("transaction", "readwrite").Call("objectStore", "employee").Call("add", `{ id: "00-01", name: "Karam", age: 19, email: "[email protected]" }`)
c := make(chan int)
<-c
}
我得到的錯誤是:
# command-line-arguments
./wasm.go:21:14: this.result undefined (type js.Value has no field or method result)
./wasm.go:41:17: cannot use dbx (type js.Value) as type string in argument to js.Global().Get
為了用 JavaScript 映射它,我想要這個go:
dbOk = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
defer dbOk.Release()
dbx := this.result
fmt.Println("this is: ", dbx)
js.Global().Call("alert", "ok.")
return nil
})
db.Set("onsuccess", dbOk)
與此 JavaScript 等效:
var dbx
request.onsuccess = function(event) {
dbx = request.result;
console.log("success: " dbx);
};
這個代碼:
js.Global().Get(dbx).Call("transaction", "readwrite").Call("objectStore", "employee").Call("add", `{ id: "00-03", name: "Karam", age: 19, email: "[email protected]" }`)
要替換此 JavaScript 代碼:
dbx.transaction(["employee"], "readwrite")
.objectStore("employee")
.add({ id: "00-03", name: "Karam", age: 19, email: "[email protected]" });
uj5u.com熱心網友回復:
在這種情況下,this是一個 Javascript 物件,因此您必須獲取result它的屬性:
result:=this.Get("result")
該result會是一個js.Value,你可以得到它的圍棋值,如果它是一個原始的,或下降,以進一步物件元素使用result.Get(),或Call它的方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358283.html
標籤:走
