Scala JS扩展HTMLElement以生成CustomElement

时间:2017-11-26 02:34:51

标签: javascript web-component scala.js

摆弄ScalaJS,我试图实现以下目标,即。创建自定义Web组件框架:

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);

所以我谦卑地开始这个

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!")
  }
}

似乎让sbt 开心

但是当我尝试在Chrome中实例化该类时:

> new mycomponent.DocumentPreview()

返回:

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

我有什么可以开始的?最后,我习惯打电话

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

修改

尝试按照建议修改build.sbt(?)

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 个答案:

答案 0 :(得分:1)

必须使用实际的ECMAScript 2015 class来声明自定义Web组件。使用functionprototype的ES 5.1样式类不能用于此。

现在,默认情况下,Scala.js会发出符合ECMAScript 5.1标准的代码,这意味着class会被编译为ES 5函数和原型。您需要通过启用ECMAScript 2015输出来告诉Scala.js生成实际的JavaScript class。这可以在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) }
  )

另请参阅extending HTMLElement: Constructor fails when webpack was used这是一个非常类似的问题,其中源代码在JavaScript中,但使用Webpack将其编译为ECMAScript 5.1。