【问题标题】:'x' is not a function when passing parameters in Kotlin Javascript在 Kotlin Javascript 中传递参数时,'x' 不是函数
【发布时间】:2017-06-21 16:40:58
【问题描述】:

我不断收到此错误:TypeError: Scraper.dumpTitle is not a function

我不知道为什么......

索引.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Kotlin JS Demo</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script src="out/production/lib/kotlin.js"></script>
<script src="out/production/Scraper.js"></script>
    <!--<script>-->
        <!--function loaded() {-->
        <!--}-->
    <!--</script>-->

    <script>
        $(function() {
            Scraper.dumpTitle(document)
        })

    </script>

</body>
</html>

Main.js

import kotlin.browser.document

/**
 *  *
 *  * -
 */
fun main(args: Array<String>) {
    println("Hello")
}

fun dumpTitle(doc: dynamic) {
    println(doc.title)
}
fun dumpTitle1() {
    println(document.title)
}

生成的js

if (typeof kotlin === 'undefined') {
  throw new Error("Error loading module 'Scraper'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'Scraper'.");
}
var Scraper = function (_, Kotlin) {
  'use strict';
  var println = Kotlin.kotlin.io.println_s8jyv4$;
  function main(args) {
    println('Hello');
  }
  function dumpTitle(doc) {
    println(doc.title);
  }
  function dumpTitle1() {
    println(document.title);
  }
  _.main_kand9s$ = main;
  _.dumpTitle_za3rmp$ = dumpTitle;
  _.dumpTitle1 = dumpTitle1;
  Kotlin.defineModule('Scraper', _);
  main([]);
  return _;
}(typeof Scraper === 'undefined' ? {} : Scraper, kotlin);

注释

  1. 调用dumpTitle1() 工作正常.. 所以我遇到的问题只是传递参数
  2. 无需指出我可以在 Kotlin 中访问 document 变量而无需传递它,我知道...但我想传递另一个 document 对象以使用

【问题讨论】:

    标签: kotlin kotlin-interop


    【解决方案1】:

    如果您从 JavaScript 调用 Kotlin 函数,则需要使用 @JsName 注释为其指定一个稳定的名称。有关文档,请参阅 here

    @JsName("dumpTitle")
    fun dumpTitle(doc: dynamic) {
        println(doc.title)
    }
    

    【讨论】:

    • 好的,谢谢,我会尝试,我浏览了文档的那部分,因为我认为它仅适用于重载函数。现在我知道了
    • 哦,顺便说一句。 .应该是动态的还是类型文档?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-23
    相关资源
    最近更新 更多