Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Javascript apply() from Scala.js?

Tags:

scala.js

How can I call a function named apply() defined on a Javascript object from Scala.js code?

The obvious solution does not work since apply is always compiled into a function call on its parent object by Scala.JS (?):

var test = {
  apply: function(idx) {...},
  apple: function(idx) {...}
}
trait Test extends js.Object {
  def apple(idx: Int) : Int = ???
  def apply(idx: Int) : Int = ???
}

val test = js.Dynamic.global.test.asInstanceOf[Test]

test.apple(1) // works, of course

test.apply(1) // does not work (seems to be compiled into the call test(1) ?)

js.Dynamic.global.test.apply(1) // does not work either
like image 649
jokade Avatar asked Aug 19 '14 10:08

jokade


1 Answers

You can annotate the apply method in your facade type with @JSName("apply"). This will yield the desired behavior:

trait Test extends js.Object {
  def apple(idx: Int) : Int = ???
  @JSName("apply")
  def apply(idx: Int) : Int = ???
}

Testing:

val test = js.Dynamic.literal(
    apply = (idx: Int) => idx,
    apple = (idx: Int) => idx
).asInstanceOf[Test]

test.apple(1) // -> 1
test.apply(1) // -> 1

For the dynamically typed case, you'll have to invoke applyDynamicNamed manually:

val dyn = test.asInstanceOf[js.Dynamic]

dyn.applyDynamicNamed("apply")(1) // -> 1
like image 74
gzm0 Avatar answered Oct 29 '22 17:10

gzm0