【问题标题】:How to call Javascript function from Kotlin code?如何从 Kotlin 代码调用 Javascript 函数?
【发布时间】:2017-08-29 02:12:06
【问题描述】:

我正在尝试将 Kotlin 代码编译为 Javascript。在我的代码中,我需要将字符串编码为 URI。我的 2 个变体都编译失败:

class PlaceholderJS(prefix: String, placeholder: String?): Placeholder(prefix, placeholder) {
override fun encode(str: String): String {
    return encodeURIComponent(str)
}

在这段代码中编译器找不到函数encodeURIComponent(str),根据https://www.w3schools.com/jsref/jsref_encodeuricomponent.asp,所有浏览器都支持。

替代方案:

class PlaceholderJS(prefix: String, placeholder: String?): Placeholder(prefix, placeholder) {
override fun encode(str: String): String {
    return URLEncoder.encode(str, Charsets.UTF_8.name())
} 

找不到 Java 类 URLEncoder(导入到文件中,就像在 Java 中一样)。这在为 JVM 编译时有效,但不适用于 JS。

我还标记了 Kotlin 模块:

compileKotlin2Js.kotlinOptions.moduleKind = "umd"

【问题讨论】:

    标签: javascript compilation kotlin


    【解决方案1】:

    我发现在 Kotlin 中声明 Javascript 函数的最新方法是:

    external fun encodeURIComponent(str: String): String
    

    一旦将它添加到 Kotlin 类中,一切都会顺利编译。

    【讨论】:

      猜你喜欢
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-21
      • 1970-01-01
      • 2015-06-20
      相关资源
      最近更新 更多