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

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

The obvious solution does not work, since apply always compiled into a function call on its parent object in 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 
+5
source share
1 answer

You can annotate the apply method in your facade type with @JSName("apply") . This will give 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 a dynamically typed case, you have to manually call applyDynamicNamed :

 val dyn = test.asInstanceOf[js.Dynamic] dyn.applyDynamicNamed("apply")(1) // -> 1 
+5
source

Source: https://habr.com/ru/post/1200660/


All Articles