玩弄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"
)发布于 2017-11-26 11:20:49
必须使用实际的ECMAScript 2015 classes来声明自定义Web组件。不能使用使用function和prototypes的ES5.1样式类。
现在,默认情况下,Scala.js发布符合ECMAScript 5.1的代码,这意味着classes被编译成ES 5函数和原型。您需要告诉Scala.js通过启用ECMAScript 2015输出来生成实际的ECMAScript classes。这可以在您的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。
https://stackoverflow.com/questions/47492492
复制相似问题