0

Question about scalajs and javascript.

How to mark a function to be purely exported to global scope?

Given scala object in top level package

@JSExport
object Foo{
 def apply(a: Int, b: Int): String = "bar"+a+b
}

I would like to compile this scala code into javascript and have this function named Foo in global scope. In other words I would like to have a javascript similar to this:

function Foo(a,b) {
    return 'bar'+a+b;
}

Is it possible using scalajs?

I am writing component in javascript, which will be referenced from third party API which can not be influenced by me. This is why I simply need to follow their rules and provide javascript functions in global scope.

pawel.panasewicz
  • 1,831
  • 16
  • 27
  • Hmm -- unusual request. How does the API work? It's expecting you to pass the *name* of a function defined in global scope, or something like that? – Justin du Coeur Dec 17 '15 at 20:37
  • API requires to define script with functions in global scope with specific names, like for example ```function anything() {...}``` which will be called whenever any event occurs. See https://docs.cycling74.com/max7/vignettes/jsbasic for more details. – pawel.panasewicz Dec 17 '15 at 22:22
  • Actually, this is a dup: http://stackoverflow.com/questions/27440235/using-scala-js-method-as-callback – gzm0 Dec 18 '15 at 09:32

2 Answers2

2

The solution to this is now Top Level Exports, as documented under the now-closed issue #1381 - to use this feature, tag a function in an object with @JSExportTopLevel.

object A {
  @JSExportTopLevel("foo")
  def foo(x: Int): Int = x + 1
}

<Foo will be available from JavaScript's global namespace>

(See https://www.scala-js.org/doc/interoperability/export-to-javascript.html for the official documentation, under "Exporting top-level methods".)

Zoey
  • 2,391
  • 2
  • 22
  • 28
1

You currently cannot do this without executing some code. But you can have setup code that assigns it:

import scala.scalajs.js

object App extends js.JSApp {
  def main(): Unit = {
    js.Dynamic.global.anything = // your js.FunctionN

  }
}

There is an issue open (#1381) to have language support for this.

gzm0
  • 14,752
  • 1
  • 36
  • 64