How to embed javascript code directly in scala.js?

这一生的挚爱 提交于 2019-12-18 15:17:10

问题


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.

Is there anyway to embed some javascript code directly? e.g. as strings?


回答1:


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.

The ugly workaround: 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');")

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

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)

You can even write crazy JavaScript-ish code like this:

if (g.console)
  (g.console.error || g.console.log).call(g.console, x)

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.



来源:https://stackoverflow.com/questions/28656170/how-to-embed-javascript-code-directly-in-scala-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!