How can I access the new javascript keyword from scala.js?

I am moving the JavaScript library to Scalajs. JS objects are created with a new keyword on the JavaScript side, so this is what I do in most cases.

trait Point extends js.Object {
  def normalize(length: Double): Point = js.native
}

This seems to work well for methods, however it does not work for constructors.

@JSName("paper.Point")
object PointNative extends js.Object {
  def apply(props: RectProps): Rectangle = js.native
}

The code above does not work. It passes type checks and compilation, but at runtime it returns undefined.

If I changed PointNative, then everything is fine.

import js.Dynamic.{ global => g, newInstance => jsnew }
object PointNative {
  def apply(props: RectProps): Rectangle = jsnew(g.paper.Point)(props).asInstanceOf[Point]
}

Is there a way to use @JSName and js.native with a new keyword?

Thank!

+4
source share
1 answer

JavaScript API paper.Point new, PointNative :

@JSName("paper.Point")
class PointNative(props: PointProps) extends js.Object {
  ...
}

new PointNative(props)

JavaScript.

PointNative(props)

, js.Object apply():

object PointNative {
  def apply(props: PointProps): PointNative = new PointNative(props)
}

, PointNative js.Object ( paper.Point), apply() :

implicit class PointNativeCompanionOps(val self: PointNative.type) extends AnyVal {
  def apply(props: PointProps): PointNative = new PointNative(props)
}
+6

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


All Articles