Scala JS Extending HTMLElement to Create a Custom Element

Using ScalaJS, I am trying to achieve the following, i.e. create your own web component skeleton:

class DocumentPreview extends HTMLElement {
  static get observedAttributes() { return []; }
  constructor() {
    super();
    this.root = this.attachShadow({ mode: "open"});
  }

  connectedCallback() {
    let x = document.querySelector('link[rel="import"]#templates').import;
    this.root.appendChild(x.querySelector("#document-preview").content.cloneNode(true));
  }

  disconnectedCallback() {
  }
  attributeChangedCallback(name, oldValue, newValue) {
  }

  get document() {

  }

}

customElements.define("document-preview", DocumentPreview);

So, I start humbly with this

package mycomponent
import scala.scalajs.js
import scala.scalajs.js.annotation.JSExportTopLevel
import scala.scalajs.js.annotation.ScalaJSDefined
import scala.scalajs.js.annotation.JSExport
import org.scalajs.dom
import org.scalajs.dom.html
import org.scalajs.dom.raw.HTMLElement
import scala.util.Random

@JSExport
@ScalaJSDefined
class DocumentPreview extends HTMLElement {
  def connectedCallback(): Unit = {
    println("Connected!")
  }
  def disconnectedCallback(): Unit = {
    println("Disconnected!")
  }
}

which seems to make sbt happy:

But when I try to instantiate a class in Chrome:

> new mycomponent.DocumentPreview()

this returns:

Uncaught TypeError: Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function

What do I need to get started? In the end, I'm used to calling

    customElements.define("document-preview", DocumentPreview);

EDIT

Trying to change build.sbtas suggested (?)

import org.scalajs.core.tools.linker.standard._

enablePlugins(ScalaJSPlugin, WorkbenchPlugin)

name := "MyComponent"

version := "0.1-SNAPSHOT"

scalaVersion := "2.11.8"

// in a single-project build:
scalaJSLinkerConfig ~= { _.withOutputMode(OutputMode.ECMAScript2015) }

libraryDependencies ++= Seq(
  "org.scala-js" %%% "scalajs-dom" % "0.9.1"
)
+1
source share
1 answer

- ECMAScript 2015 class es. ES 5.1 function prototype .

Scala.js ECMAScript 5.1 , , class es ES 5. Scala.js JavaScript class es, ECMAScript 2015. build.sbt :

import org.scalajs.core.tools.linker.standard._

// in a single-project build:
scalaJSLinkerConfig ~= { _.withOutputMode(OutputMode.ECMAScript2015) }

// in a multi-project build:
lazy val myJSProject = project.
  ...
  settings(
    scalaJSLinkerConfig ~= { _.withOutputMode(OutputMode.ECMAScript2015) }
  )

. HTMLElement: -, , JavaScript, Webpack ECMAScript 5.1.

+1

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


All Articles