繁体   English   中英

使用 coffeescript 创建自定义 web 组件时出错

[英]errors creating a custom web component with coffeescript

我正在尝试在 Rails 应用程序中创建自定义 HTML5 web 组件,但是在实例化 Javascript268CFDE6331C4BEB6 时出现错误

版本信息:
导轨 4.2.11.3
ruby 2.5.8
咖啡轨 4.1.1

我在一个最小的 Rails 应用程序中重现了这个问题,在https://github.com/fredwillmore/coffee_test

这是创建组件的coffeescript文件:

class ThingDoer extends HTMLElement
  # constructor: ->
  #   super()

customElements.define("thing-doer", ThingDoer);

这是coffeescript转译为:

ThingDoer = (function(superClass) {
    extend(ThingDoer, superClass);

    function ThingDoer() {
      return ThingDoer.__super__.constructor.apply(this, arguments);
    }

    return ThingDoer;

  })(HTMLElement);

customElements.define("thing-doer", ThingDoer);

错误:

没有定义构造函数,我收到以下错误:

未捕获的类型错误:无法构造“HTMLElement”:请使用“新”运算符,此 DOM object 构造函数不能作为 function 调用。

与只调用“super”的构造函数相同:

未捕获的类型错误:无法构造“HTMLElement”:请使用“新”运算符,此 DOM object 构造函数不能作为 function 调用。

我尝试了一个只调用new HTMLElement的构造函数:

未捕获的类型错误:非法构造函数

我错过了什么?

编译后的脚本不适合,因为 class 已编译为与自定义元素 API 不兼容的 ES5 样式 class。

相反,您可以编写一点原始 JavaScript 来生成真正的 class,然后使用CoffeeScript 的原型 Inheritance 语法为其增加更多方法:

ThingDoer = `class ThingDoer extends HTMLElement { constructor() { super(); this.initialize(); } }`

ThingDoer::initialize = ->
  @innerHTML = 'meow'

customElements.define "thing-doer", ThingDoer

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM