这是基于GitHub的scala-js-example-app。
我有一个我想在Javascript中定义的函数,并且还没有由Scala.js库定义。
在我的ScalaJSExample.scala文件副本中,我有:
object Mine extends js.Object {
def foobarfoo():String = ??? //this is just a simple example and I know this can be done completely in Scala, but just go with it.
}
object ScalaJSExample extends js.JSApp {
def main(): Unit = {
val paragraph = dom.document.createElement("p")
paragraph.innerHTML = "<strong>It works!" + Mine.foobarfoo() + ".</strong>"
dom.document.getElementById("playground").appendChild(paragraph)
}
/** Computes the square of an integer.
* This demonstrates unit testing.
*/
def square(x: Int): Int = x*x
}
现在我想在Javascipt中定义foobarfoo。
我试过在javascript文件中写这个:
function foobarfoo() { return "Hello, World!"; }
这不起作用,所以我尝试了更多的Scala.js语法:
var Mine = {
foobarfoo: function() { return "Hello, World!"; }
}
以及许多其他变体,但这些都没有奏效,我无法得到“Hello,World!”编译后出现在网页上。
我应该如何编写foobarfoo()以获得正确的结果?
答案 0 :(得分:0)
恢复讨论,问题是包含顺序:OP在Scala.js代码之后添加了自定义JavaScript函数:
<script type="text/javascript" src="./target/scala-2.11/example-opt.js"></script>
<script type="text/javascript" src="./target/scala-2.11/example-launcher.js"></script>
<script type="text/javascript" src="src/main/scala/example/myscript.js"></script>
因此,找不到请求的功能。将myscript.js
置于顶端解决了问题:
<script type="text/javascript" src="src/main/scala/example/myscript.js"></script>
<script type="text/javascript" src="./target/scala-2.11/example-opt.js"></script>
<script type="text/javascript" src="./target/scala-2.11/example-launcher.js"></script>