' X'在Kotlin Javascript中传递参数时不是函数

时间:2017-06-21 16:40:58

标签: kotlin kotlin-interop

我一直收到此错误: TypeError:Scraper.dumpTitle不是函数

我无法弄清楚为什么......

的index.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对象来使用

1 个答案:

答案 0 :(得分:3)

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

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