Trying with GO WebAssembly accessing the browser IndexedDB, with the below code I was able to create the ibdexedDB, but I got an error while trying to access it using js.Global().Get(dbx)
or even trying to access 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
}
The error I got is:
# 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
To map it with JavaScript, I wanted this 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)
To be equivalent to this JavaScript:
var dbx
request.onsuccess = function(event) {
dbx = request.result;
console.log("success: " dbx);
};
And this go code:
js.Global().Get(dbx).Call("transaction", "readwrite").Call("objectStore", "employee").Call("add", `{ id: "00-03", name: "Karam", age: 19, email: "[email protected]" }`)
To replace this JavaScript code:
dbx.transaction(["employee"], "readwrite")
.objectStore("employee")
.add({ id: "00-03", name: "Karam", age: 19, email: "[email protected]" });
CodePudding user response:
In this context, this
is a Javascript object, so you have to get the property result
of it:
result:=this.Get("result")
The result
will be a js.Value
, and you can get the the Go value of it if it is a primitive, or descend to further object elements using result.Get()
, or Call
a method of it.