Golang中WASM构建时如何使用可选参数
Golang中WASM构建时如何使用可选参数 我正在尝试将以下来自IndexedDB JavaScript API的代码转换为GO WASM:
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("employee", {keyPath: "id"});
for (var i in employeeData) {
objectStore.add(employeeData[i]);
}
}
因此,我编写了:
var dbUpgrade js.Func
var result, request js.Value
dbUpgrade = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
defer dbUpgrade.Release()
result = this.Get("result")
var objectStore = result.Call("createObjectStore", "employee")
objectStore.Call("add", `{ id: "00-01", name: "Karam", age: 19, email: "kenny@planet.org" }`)
window.Call("alert", "First record posted.")
return nil
})
request.Set("onupgradeneeded", dbUpgrade)
但我遇到了以下运行时错误:
panic: JavaScript error: Failed to execute 'add' on 'IDBObjectStore': The object store uses out-of-line keys and has no key generator and the key parameter was not provided.
我理解原因是因为在 result.Call("createObjectStore", "employee" 处没有包含 {keyPath: "id"} 来匹配JavaScript的代码,但我尝试了以下方法,都没有成功:
// 1.
result.Call("createObjectStore", "employee", "{keyPath: `id`}")
// 2.
key, _ := json.Marshal(map[string]string{"keyPath": "id"})
result.Call("createObjectStore", "employee", key)
// 3.
result.Call("createObjectStore", `"employee", "{keyPath: "id"}"`)
有什么想法可以解决这个问题吗?
更多关于Golang中WASM构建时如何使用可选参数的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于Golang中WASM构建时如何使用可选参数的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Go WASM中传递JavaScript对象参数需要使用js.ValueOf将Go的map转换为JavaScript对象。以下是正确的实现方式:
var dbUpgrade js.Func
var result, request js.Value
dbUpgrade = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
defer dbUpgrade.Release()
result = this.Get("result")
// 创建JavaScript对象作为可选参数
options := map[string]interface{}{
"keyPath": "id",
}
jsOptions := js.ValueOf(options)
// 传递JavaScript对象参数
var objectStore = result.Call("createObjectStore", "employee", jsOptions)
// 添加数据时需要提供键值
employeeData := map[string]interface{}{
"id": "00-01",
"name": "Karam",
"age": 19,
"email": "kenny@planet.org",
}
jsEmployeeData := js.ValueOf(employeeData)
objectStore.Call("add", jsEmployeeData)
window.Call("alert", "First record posted.")
return nil
})
request.Set("onupgradeneeded", dbUpgrade)
如果需要添加多个员工数据,可以使用循环:
employees := []map[string]interface{}{
{"id": "00-01", "name": "Karam", "age": 19, "email": "kenny@planet.org"},
{"id": "00-02", "name": "Alice", "age": 25, "email": "alice@example.com"},
}
for _, emp := range employees {
jsEmp := js.ValueOf(emp)
objectStore.Call("add", jsEmp)
}
对于更复杂的配置选项,比如包含autoIncrement:
options := map[string]interface{}{
"keyPath": "id",
"autoIncrement": false,
}
jsOptions := js.ValueOf(options)
var objectStore = result.Call("createObjectStore", "employee", jsOptions)
关键点是使用js.ValueOf()将Go的map转换为JavaScript对象,这样就能正确传递可选参数给JavaScript API。

