如何直接在scala.js中嵌入javascript代码? [英] How to embed javascript code directly in scala.js?
问题描述
当我使用scala.js编写scala代码来生成javascript时,我发现有时很难将第三方javascript代码包装到scala对象中。
When I use scala.js to write scala code to generate javascript, I found it difficult sometimes to wrap the 3rd-party javascript code into scala objects.
是无论如何直接嵌入一些JavaScript代码?例如作为字符串?
Is there anyway to embed some javascript code directly? e.g. as strings?
推荐答案
不,故意没有。例如,嵌入式JavaScript代码中的标识符如何绑定到周围Scala.js代码中的标识符?这永远不会有任何意义。
No, there isn't, on purpose. How would identifiers in the "embedded" JavaScript code bind to identifiers in the surrounding Scala.js code, for example? That would never make any sense.
您可以将JavaScript代码作为参数嵌入到 js.eval
功能,显然。
You can "embed" JavaScript code as a parameter to the js.eval
function, obviously.
import scala.scalajs.js
def foo(x: Int): Unit =
js.eval("console.error('hello');")
但是 js.eval
总是在全局范围内评估(不在你调用它的范围内),所以这不起作用:
But js.eval
always evaluates in the global scope (not in the scope where you call it), so this doesn't work:
def foo(x: Int): Unit =
js.eval("console.error(x);") // x undefined here
好的解决方案: js.Dynamic
虽然您无法在Scala.js代码中嵌入任意JavaScript代码,但您可以使用 js.Dynamic
和 js.DynamicImplicits
。有了这些,您通常可以使用JavaScript语义将JavaScript代码直接转换为Scala语法(非常接近JS语法):
The good solution: js.Dynamic
Although you cannot embed arbitrary JavaScript code in Scala.js code, you can use js.Dynamic
and js.DynamicImplicits
. With those, you can typically transliterate JavaScript code directly into Scala syntax (which is very close to JS syntax) with the "JavaScript semantics":
import scala.scalajs.js
import js.DynamicImplicits._
import js.Dynamic.{global => g}
def foo(x: Int): Unit =
g.console.error(x)
您甚至可以编写疯狂的JavaScript-ish代码:
You can even write crazy JavaScript-ish code like this:
if (g.console)
(g.console.error || g.console.log).call(g.console, x)
如果你想对 console
或 console.error
不存在,例如。
if you want to be robust against console
or console.error
not existing, for example.
这种方法的优点是标识符的正常绑定规则。而且您不必使用字符串来完成工作。
The advantage of this approach is that normal binding rules for identifiers. And you don't have to resort to strings to get the job done.
这篇关于如何直接在scala.js中嵌入javascript代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!