Thursday 7 January 2021

Passing DOM element to 3rd-party class constructor fails in ScalaJS

In this simple web page, I'm trying to create a Handsontable grid:

<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<body>
  <div id="grid-viewer"></div>
</body>

<script src="https://cdn.jsdelivr.net/npm/handsontable@8.2.0/dist/handsontable.full.js"></script>

<!-- SOLUTION 1 -->
<script type="text/javascript" src="./grid.js"></script>

<!-- SOLUTION 2 -->
<script type="text/javascript" src="./target/scala-2.13/scalajs-bundler/main/grid-fastopt-bundle.js"></script>

</html>

Solution 1 is the pure JavaScript implementation, which works fine:

const config = {
    data: [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ],
    rowHeaders: true,
    colHeaders: true,
    licenseKey: "non-commercial-and-evaluation"
}

window.addEventListener('load', ev => {
    const element = document.getElementById('grid-viewer');
    const grid = new Handsontable(element, config);

    console.log(element);  // prints <div>...</div>
    console.log(config);   // prints the object { … }
});

Solution 2 is a Scala.js implementation which is a literal translation from the code above, with the added façade for the 3rd party library (Handsontable stores its constructor in the window object):

package example

import org.scalajs.dom
import scala.scalajs.js
import scala.scalajs.js.annotation.JSGlobal

@js.native
@JSGlobal("Handsontable")
class Handsontable(element: dom.raw.Element, conf: js.Object) extends js.Object

object Example {
  def main(args: Array[String]): Unit = {
    object config extends js.Object {
      val data = List(
        List(1, 2, 3),
        List(4, 5, 6),
        List(7, 8, 9)
      )
      val rowHeaders = true
      val colHeaders = true
      val licenseKey = "non-commercial-and-evaluation"
    }

    dom.window.addEventListener("load", { ev: dom.Event =>
      val element = dom.document.getElementById("grid-viewer")
      val grid = new Handsontable(element, config)

      println(element)  // prints [object HTMLDivElement]
      println(config)   // prints [object Object]
    })
  }

}

The Scala.js solution calls the constructor but then fails with TypeError: element is undefined. The output of the println call makes me believe that element is not the element itself but a wrapper.

This is my sbt configuration:

enablePlugins(ScalaJSPlugin)        // 1.3.1
enablePlugins(ScalaJSBundlerPlugin) // 0.20.0

scalaVersion := "2.13.4"

scalaJSUseMainModuleInitializer := true

libraryDependencies += "org.scala-js" %%% "scalajs-dom" % "1.1.0"

Why does my Scala.js program behave different than the equivalent JS program? Is my façade defined correctly?



from Passing DOM element to 3rd-party class constructor fails in ScalaJS

No comments:

Post a Comment