【问题标题】:How can I use js.Value as argument to js.Global().Get如何使用 js.Value 作为 js.Global().Get 的参数
【发布时间】:2021-11-15 14:44:04
【问题描述】:

尝试使用 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" });

【问题讨论】:

    标签: go webassembly


    【解决方案1】:

    在此上下文中,this 是一个 Javascript 对象,因此您必须获取它的属性 result

    result:=this.Get("result")
    

    result 将是一个js.Value,如果它是一个原始值,您可以获取它的 Go 值,或者使用result.Get()Call 它的一种方法下降到更多对象元素。

    【讨论】:

    猜你喜欢
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    相关资源
    最近更新 更多