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?
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?
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.But
js.eval
always evaluates in the global scope (not in the scope where you call it), so this doesn't work:The good solution:
js.Dynamic
Although you cannot embed arbitrary JavaScript code in Scala.js code, you can use
js.Dynamic
andjs.DynamicImplicits
. With those, you can typically transliterate JavaScript code directly into Scala syntax (which is very close to JS syntax) with the "JavaScript semantics":You can even write crazy JavaScript-ish code like this:
if you want to be robust against
console
orconsole.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.