尝试使用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: "kenny@planet.org" }`)
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);
};
这个go代码:
js.Global().Get(dbx).Call("transaction", "readwrite").Call("objectStore", "employee").Call("add", `{ id: "00-03", name: "Karam", age: 19, email: "kenny@planet.org" }`)
替换此JavaScript代码:
dbx.transaction(["employee"], "readwrite")
.objectStore("employee")
.add({ id: "00-03", name: "Karam", age: 19, email: "kenny@planet.org" });
在这种情况下,this
是一个Javascript对象,因此您必须获得它的属性result
:
result:=this.Get("result")
result
将是一个js.Value
,如果它是一个基元,您可以获得它的Go值,或者使用result.Get()
或Call
(它的一种方法(下降到其他对象元素。