简体   繁体   English

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

[英]errors creating a custom web component with coffeescript

I am trying to create a custom HTML5 web component in a Rails application, but I am getting errors instantiating the Javascript object.我正在尝试在 Rails 应用程序中创建自定义 HTML5 web 组件,但是在实例化 Javascript268CFDE6331C4BEB6 时出现错误

Version info:版本信息:
Rails 4.2.11.3导轨 4.2.11.3
ruby 2.5.8 ruby 2.5.8
coffee-rails 4.1.1咖啡轨 4.1.1

I've reproduced the issue in a minimal Rails app, available at https://github.com/fredwillmore/coffee_test我在一个最小的 Rails 应用程序中重现了这个问题,在https://github.com/fredwillmore/coffee_test

Here's the coffeescript file that creates the component:这是创建组件的coffeescript文件:

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

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

This is what the coffeescript transpiles to:这是coffeescript转译为:

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

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

    return ThingDoer;

  })(HTMLElement);

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

Errors:错误:

with no constructor defined, I get the following error:没有定义构造函数,我收到以下错误:

Uncaught TypeError: Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function.未捕获的类型错误:无法构造“HTMLElement”:请使用“新”运算符,此 DOM object 构造函数不能作为 function 调用。

same with a constructor that just calls "super":与只调用“super”的构造函数相同:

Uncaught TypeError: Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function.未捕获的类型错误:无法构造“HTMLElement”:请使用“新”运算符,此 DOM object 构造函数不能作为 function 调用。

I tried a constructor that just calls new HTMLElement :我尝试了一个只调用new HTMLElement的构造函数:

Uncaught TypeError: Illegal constructor未捕获的类型错误:非法构造函数

What am I missing?我错过了什么?

The compiled script isn't suitable as the class has been compiled to an ES5-style class which is not compatible with Custom Elements API.编译后的脚本不适合,因为 class 已编译为与自定义元素 API 不兼容的 ES5 样式 class。

Instead, you can write a little bit of raw JavaScript to generate a real class, then augment more methods to it using the CoffeeScript's Prototypal Inheritance syntax :相反,您可以编写一点原始 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