0

我正在尝试使用 kotlin-js 注册一个网络消息频道,但无法确定如何访问该MessageEventInit类型。

https://kotlinlang.org/api/latest/jvm/stdlib/org.w3c.dom/-message-event-init/index.html

window.addEventListener方法只公开一个泛型Event类型

https://kotlinlang.org/api/latest/jvm/stdlib/org.w3c.dom.events/-event-target/add-event-listener.html

fun addEventListener(
    type: String,
    callback: EventListener?,
    options: dynamic = definedExternally)
fun addEventListener(
    type: String,
    callback: ((Event) -> Unit)?,
    options: dynamic = definedExternally)

到目前为止,这是我想出的,但是很难构建该项目。

fun configureChannel() {
    val channel = MessageChannel()
    var jsPortOne = channel.port1
    var jsPortTwo = channel.port2

    window.addEventListener("message", {
    }, false)

    jsPortOne.addEventListener("message", {
        window.alert((it as MessageEvent).data.toString())
    }, false)

    jsPortTwo.addEventListener("message", {
        window.alert((it as MessageEvent).data.toString())
    }, false)

    jsPortOne.start()
    jsPortTwo.start()
}

我的主要目标是将此文件转换为 Kotlin/JS 并将其与此 kotlin android 项目结合起来

https://github.com/darran-kelinske-fivestars/cordova-alternative-pattern/blob/master/app/src/main/assets/js/index.js

4

1 回答 1

0

预感是正确的。我能够构建和部署项目。要在 Kotlin/JS 中使用MessageEvent类型,您需要将事件转换为MessageEvent

val event = it as MessageEvent

这是一个示例:

@JsName("configureChannel")
fun configureChannel() {
    console.log("Configuring channel")
    window.addEventListener("message", {

        val event = it as MessageEvent

        if (event.data != KEY_CAPTURE_PORT) {
            console.log("event.data: ${event.data}")
            inputPort.postMessage(event.data)
        } else if (event.data == KEY_CAPTURE_PORT) {
            console.log("assigning captured port")
            outputPort = event.ports[0]
        }
    }, false)

    inputPort.start()
    outputPort.start()
}
于 2020-03-07T04:36:16.367 回答