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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With